简体   繁体   中英

Populating dictionary values from a list

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}

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}

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}

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM