Is it possible to Zip a python Dictionary and List together?
For Example:
dict = {'A':1, 'B':2, 'C':3}
num_list = [1, 2, 3]
zipped = zip(dict, num_list)
Then I'd like to do something like this:
for key, value, num_list_entry in zipped:
print key
print value
print num_list_entry
I haven't found a solution for this, so I'm wondering how do I go about doing this?
You can use iteritems().
dictionary = {'A':1, 'B':2, 'C':3}
num_list = [1, 2, 3]
zipped = zip(dictionary.iteritems(), num_list)
for (key, value), num_list_entry in zipped:
print key
print value
print num_list_entry
Note: do not shadow the built-in dict. This will one day come back to haunt you.
Now, as for your issue, simply use dict.items:
>>> d = {'A':1, 'B':2, 'C':'3'}
>>> num_list = [1, 2,3 ]
>>> for (key, value), num in zip(d.items(), num_list):
... print(key)
... print(value)
... print(num)
...
A
1
1
C
3
2
B
2
3
>>>
Note: Dictionaries aren't ordered, so you have no guarantee on the order of the items when iterating over them.
Additional Note: when you iterate over a dictionary, it iterates over the keys:
>>> for k in d:
... print(k)
...
A
C
B
Which makes this common construct:
>>> for k in d.keys():
... print(k)
...
A
C
B
>>>
Redundant, and in Python 2, inefficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With