Why not use zipped list instead of zip function to create dict?


#1

Given this:
drinks = [“espresso”, “chai”, “decaf”, “drip”]
caffeine = [64, 40, 0, 120]

Why does this command work:
drinks_to_caffeine = {key:value for key, value in zip(drinks,caffeine)}

but this one produces an empty list:
zipped_drinks = zip(drinks,caffeine)
drinks_to_caffeine = {key:value for key, value in zipped_drinks}


#2

Dictionaries do not require an index, or any order. The data is directly associative to a corresponding key. This is stricter since keys are a set.

As dict the data is more easily accessible on direct look up. If we know the key, we can poll the value.

The why it doesn’t work is the double variables in a for loop. Enumerate the zip object to poll tuple pairs simultaneously would be my first thought on how to approach this.


>>> zipped_drinks = zip(drinks,caffeine)
>>> z = list(zipped_drinks)
>>> z
[('espresso', 64), ('chai', 40), ('decaf', 0), ('drip', 120)]
>>> d2c = {z[x][0]:z[x][1] for x in range(len(z))}
>>> d2c
{'decaf': 0, 'drip': 120, 'chai': 40, 'espresso': 64}
>>> 

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.