2

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...}?

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Jack
  • 351
  • 2
  • 6
  • 10
  • If "my key is a list from 1 to 9" inclusive, but your value list has TEN entries, then as they say in Shanghai, you are up Suzhou Creek in a bamboo steamer with a broken chopstick for a paddle. – John Machin Nov 25 '09 at 01:56

5 Answers5

12

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":

  • the range() function in the snippet above will produce the 1 through 9 range, that is because the starting value (1, here), if provided, is always included, whereas the ending value (10, here) is never included.
  • the zip() function stops after the iteration which includes the last item of the shortest iterable (in our case, omitting '5', the last value of the list)
mjv
  • 73,152
  • 14
  • 113
  • 156
6

If you are mapping indexes specifically, use the enumerate builtin function instead of zip/range.

dict(enumerate([2,4,0,9,6,6,8,6,4,5]))
fengb
  • 1,448
  • 14
  • 15
  • 2
    Hard to see why you'd need to create a dict that uses a range for a key, unless you're passing it to something that can't use a list. – Mark Ransom Nov 24 '09 at 22:23
2
values = [2,4,0,9,6,6,8,6,4,5]
d = dict(zip(range(10), values))
int3
  • 12,861
  • 8
  • 51
  • 80
1
mydict = dict(zip(range(10), [2,4,0,9,6,6,8,6,4,5]))
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
0

should be something like

dict(zip(a,b))
Jimmy
  • 89,068
  • 17
  • 119
  • 137