Trying to make dictionary with 2 list one being the key and one being the value but I'm having a problem. This is what I have so far:
d={}
for num in range(10):
for nbr in range(len(key)):
d[num]=key[nbr]
Say my key is a list from 1 to 9, and value list is [2,4,0,9,6,6,8,6,4,5].
How do I assign so it that its like {0:2, 1:4, etc...}?
zip() to the rescue!
>>> k = range(1,10) # or some list or iterable of sorts
>>> v = [2,4,0,9,6,6,8,6,4,5]
>>> d = dict(zip(k,v))
>>> d
{1: 2, 2: 4, 3: 0, 4: 9, 5: 6, 6: 6, 7: 8, 8: 6, 9: 4}
>>>
For more details, see zip() built-in function, in Python documentation.
Note, regarding range() and the list of "keys".
The question reads "key is a list from 1 to 9" (i.e. 9 distinct keys) but the value list shows 10 distinct values. This provides the opportunity to discuss two points of "detail":
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