0

I am using list comprehension to create a dictionary. The Iterable is created using zip function on two individual lists. If print function is used to check the list of this zip object and then dictionary is being created, it produces an empty dictionary. Whereas if list of this zip element is not printed, then dictionary is created as expected. Please explain why this is happening.

drinks = ["espresso", "chai", "decaf", "drip"]
caffeine = [64, 40, 0, 120]
zipped_drinks = zip(drinks, caffeine)
print(list(zipped_drinks))
drinks_to_caffeine = {key:value for key,value in zipped_drinks}
print(drinks_to_caffeine)

This produces :- [('espresso', 64), ('chai', 40), ('decaf', 0), ('drip', 120)] {}

If "print(list(zipped_drinks))" is removed, output is :- {'espresso': 64, 'chai': 40, 'decaf': 0, 'drip': 120}

kaurp5
  • 13
  • 4
  • You should know that happen when you include `list(zipped_drinks)`. It is not just for printing but the dict itself is changed. (and will remain only the keys) – Lamanus Jul 31 '19 at 12:41

1 Answers1

0

This is because you have consumed the zip object by calling list on it and it is now empty. See this SO question and top answer. Basically zip returns an iterator in Python 3.

As you have seen you need to either remove the list call or call zip again:

drinks = ["espresso", "chai", "decaf", "drip"]
caffeine = [64, 40, 0, 120]
zipped_drinks = zip(drinks, caffeine)
print(list(zipped_drinks))
zipped_drinks = zip(drinks, caffeine)
drinks_to_caffeine = {key:value for key,value in zipped_drinks}
print(drinks_to_caffeine) 
PyPingu
  • 1,697
  • 1
  • 8
  • 21