9

I'm trying to construct a dictionary in python. Code looks like this:

dicti = {}
keys = [1, 2, 3, 4, 5, 6, 7, 8, 9]
dicti = dicti.fromkeys(keys)

values = [2, 3, 4, 5, 6, 7, 8, 9]

How can I populate values of dictionary using a list? Is there some built in function?

The result should be like this:

dicti = {1:2,2:3,3:4,4:5,5:6,6:7,7:8,8:9}
georg
  • 211,518
  • 52
  • 313
  • 390
user1455966
  • 277
  • 2
  • 4
  • 8

3 Answers3

26

If you have two lists keys and the corresponding values:

keys = [1, 2, 3, 4, 5, 6, 7, 8, 9]
values = [2, 3, 4, 5, 6, 7, 8, 9]
dicti = dict(zip(keys, values))

dicti is now {1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 8, 8: 9}

eumiro
  • 207,213
  • 34
  • 299
  • 261
  • As a note, one should be careful when using zip. It is important to notice how `zip` drops values from the longer list. This example demonstrates what would happen if someone intended to have 9 corresponding key:value pairs but missed the first value from the `values` list. Notice how the values are actually shifted by one, e.g., value 2 ended up with key 1! This may not be the intended behavior. Be sure to check that the code matches what you actually intended. – Steven C. Howell Mar 20 '17 at 15:25
1

Another one liner for your specific case would be:

dicti = {k:v for k, v in enumerate(values, start=1)}

The result is:

print(dicti)
{1:2,2:3,3:4,4:5,5:6,6:7,7:8,8:9}
anjandash
  • 797
  • 10
  • 21
0

this will work but the list have to be the same size (drop the 9 in the keys list)

keys = [1, 2, 3, 4, 5, 6, 7, 8]
values = [2, 3, 4, 5, 6, 7, 8, 9]
dicti = {}

for x in range(len(keys)):
     dicti[keys[x]] = values[x]