5

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?

Corey Goldberg
  • 59,062
  • 28
  • 129
  • 143
John Smith
  • 843
  • 2
  • 9
  • 21
  • Have you looked at what each item in `zipped` is? They don't have length three, so you can't unpack to three names like that. – jonrsharpe Jan 12 '17 at 22:44
  • 3
    **DO NOT** use dict as the name for the variable, use something like my_dict – Lucas Jan 12 '17 at 22:45
  • it's bad practice to use the name "dict" for your dictionary... it shadows the real `dict`, which is a built-in function name – Corey Goldberg Jan 12 '17 at 22:47

2 Answers2

7

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
Corey Goldberg
  • 59,062
  • 28
  • 129
  • 143
  • Thank you for your response. I'm trying to do this in a django application, but the for loop doesn't seem to work in the template. Any ideas why? – John Smith Jan 12 '17 at 23:06
  • In a django template you would do: {% for dictionary, num_list_entry in zipped %} {% with key=dictionary.0 value=dictionary.1 %} {{key}} {{value}} {{num_list entry}} {% endwith %} {% endfor %} – John Smith Jan 12 '17 at 23:53
  • Usually, we want to do this sort of thing with an ordered dictionary. Giving an example with ordered dictionary would be equally useful. – M. Mortazavi Jun 09 '22 at 17:50
6

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.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172