Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}
like image 665
user1455966 Avatar asked Jul 13 '12 09:07

user1455966


People also ask

How do you make a list into a dictionary value?

To convert dictionary values to list sorted by key we can use dict. items() and sorted(iterable) method. Dict. items() method always returns an object or items that display a list of dictionaries in the form of key/value pairs.

How do you create a dictionary from a list of keys and values?

Using zip() with dict() function The simplest and most elegant way to build a dictionary from a list of keys and values is to use the zip() function with a dictionary constructor.

Can you convert a list into a dictionary?

To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.


2 Answers

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}

like image 134
eumiro Avatar answered Nov 05 '22 16:11

eumiro


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}
like image 43
anjandash Avatar answered Nov 05 '22 15:11

anjandash