Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One liner: creating a dictionary from list with indices as keys

I want to create a dictionary out of a given list, in just one line. The keys of the dictionary will be indices, and values will be the elements of the list. Something like this:

a = [51,27,13,56]         #given list  d = one-line-statement    #one line statement to create dictionary  print(d) 

Output:

{0:51, 1:27, 2:13, 3:56} 

I don't have any specific requirements as to why I want one line. I'm just exploring python, and wondering if that is possible.

like image 450
Nawaz Avatar asked May 17 '13 11:05

Nawaz


People also ask

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 use a list as a key for a dictionary?

A dictionary or a list cannot be a key. Values, on the other hand, can literally be anything and they can be used more than once.

How do you make a dictionary one line?

Python Update Dictionary in One Line Solution: Use the square bracket notation dict[key] = value to create a new mapping from key to value in the dictionary. There are two cases: The key already existed before and was associated to the old value_old .

How do I make a dictionary out of a list?

To convert a list to a dictionary using the same values, you can use the dict. fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.


2 Answers

a = [51,27,13,56] b = dict(enumerate(a)) print(b) 

will produce

{0: 51, 1: 27, 2: 13, 3: 56} 

enumerate(sequence, start=0)

Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence:

like image 166
glglgl Avatar answered Sep 21 '22 00:09

glglgl


With another constructor, you have

a = [51,27,13,56]         #given list d={i:x for i,x in enumerate(a)} print(d) 
like image 37
kiriloff Avatar answered Sep 18 '22 00:09

kiriloff