The Python Oracle

Create a dictionary with comprehension

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5 Looping

--

Chapters
00:00 Create A Dictionary With Comprehension
00:20 Accepted Answer Score 2320
00:54 Answer 2 Score 296
01:14 Answer 3 Score 73
01:37 Answer 4 Score 53
03:16 Answer 5 Score 44
03:32 Thank you

--

Full question
https://stackoverflow.com/questions/1747...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #dictionary #listcomprehension #dictionarycomprehension

#avk47



ACCEPTED ANSWER

Score 2340


Use a dict comprehension (Python 2.7 and later):

{key: value for key, value in zip(keys, values)}

Alternatively, use the dict constructor:

pairs = [('a', 1), ('b', 2)]
dict(pairs)                          # → {'a': 1, 'b': 2}
dict((k, v + 10) for k, v in pairs)  # → {'a': 11, 'b': 12}

Given separate lists of keys and values, use the dict constructor with zip:

keys = ['a', 'b']
values = [1, 2]
dict(zip(keys, values))              # → {'a': 1, 'b': 2}



ANSWER 2

Score 299


In Python 3 and Python 2.7+, dictionary comprehensions look like the below:

d = {k:v for k, v in iterable}

For Python 2.6 or earlier, see fortran's answer.




ANSWER 3

Score 73


In fact, you don't even need to iterate over the iterable if it already comprehends some kind of mapping, the dict constructor doing it graciously for you:

>>> ts = [(1, 2), (3, 4), (5, 6)]
>>> dict(ts)
{1: 2, 3: 4, 5: 6}
>>> gen = ((i, i+1) for i in range(1, 6, 2))
>>> gen
<generator object <genexpr> at 0xb7201c5c>
>>> dict(gen)
{1: 2, 3: 4, 5: 6}



ANSWER 4

Score 44


In Python 2.7, it goes like:

>>> list1, list2 = ['a', 'b', 'c'], [1,2,3]
>>> dict( zip( list1, list2))
{'a': 1, 'c': 3, 'b': 2}

Zip them!