Python Forum

Full Version: having dictionary and list to iterate in for loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
dic = {3: 0.1, 4: 0.2, 5: 0.1, 6:0.2, 7:0.1, 8:0.2}
ls =  {0.2,   0.1,     0.2,    0.1,   0.2,   0.1}
n = {}


for i, v, l in list(dic.keys()),list(dic.values()),ls:

   add = v + l
   n[i] = add

# expected result {3: 0.3, 4: 0.3, 5: 0.3, 6:0.3, 7:0.3, 8:0.3}
print (n)
I'm trying to use keys, values of dic and entries of ls at the same time, can I do that?
 I'm not sure why it's not correct ?

Wait, I can only have one element after in ?
for i, k in enumerate(dic.keys()):
    n[k] = dic[k] + ls[i]
Did you try your code? What does happen when you run it?
(Jan-04-2017, 08:16 AM)wavic Wrote: [ -> ]
 for i, k in enumerate(dic.keys()):     
    dic[k] = dic[k] + ls[i] 
As you can't rely on the order of the dict, this is not guaranteed to give the desired result.
You would need to sort the keys to guarantee behavior with this method.
Honestly if you want to add values from a sequence where the values correspond to keys it would make more sense if both were dicts.
You're right. 
In this case enumerate(sorted(dic.keys())) would be enough.
But also, the ls is not a list
the error message is like too many things to unpack
Sorry should have used [] for list,
Oh, this seems cute, so the enumerate method turns the keys into something like [0: key0, 1: key1, 2: key2...]?
https://docs.python.org/2/library/functi...#enumerate

It adds a counter to an iterable object. 

In [1]: for counter, iterable in enumerate(range(5)):
   ...:     print(counter, iterable)
   ...:        
0 0
1 1
2 2
3 3
4 4