Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zipping a Python Dictionary and List together

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?

like image 204
John Smith Avatar asked Sep 01 '26 14:09

John Smith


2 Answers

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
like image 101
Michael Ellner Avatar answered Sep 03 '26 03:09

Michael Ellner


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.

like image 21
juanpa.arrivillaga Avatar answered Sep 03 '26 03:09

juanpa.arrivillaga