3

Possible Duplicate:
Map two lists into a dictionary in Python

I have 2 lists like this: ['one', 'two', 'three'] and [1, 2, 3]

I want to turn it into a dictionary like this {'one':1, 'two':2, 'three':3}

The catch is that i have to use comprehension. Thanks.

Community
  • 1
  • 1
Fred4106
  • 105
  • 1
  • 1
  • 8
  • 3
    Why do you have to use comprehension? – Ben Burns Oct 03 '12 at 20:06
  • It's not an exact duplicate, because "The catch is that I have to use comprehension". The accepted answer uses `dict(zip(keys, values))`; there is no answer that uses a list comprehension (although one answer uses a generator expression that could be turned into a comprehension with just two character changes.) That may be a stupid requirement, but it is a requirement, so it's not a duplicate. – abarnert Oct 03 '12 at 20:55

4 Answers4

22
keys=['one', 'two', 'three'] 
values= [1, 2, 3]
dictionary = dict(zip(keys, values)) 

>>> print dictionary
{'one': 1, 'two': 2, 'three': 3}

Take a look at builtin functions, they often become handy. You can use dict comprehensions from Python 2.7 up, but the they should not be the way to do it:

{k: v for k, v in zip(keys, values)}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
root
  • 76,608
  • 25
  • 108
  • 120
5
keys = ['one', 'two', 'three']
values = [1, 2, 3]
dict(zip(keys, values))

this is already the most pythonic way.

You can use a dict comprehension, if you really must:

{k: v for k,v in zip(keys, values)}
phihag
  • 278,196
  • 72
  • 453
  • 469
  • 1
    To be fair, the OP didn't say "list comprehension", so `d={k:v for k,v in zip(a, b)}` might qualify. (Of course `dict(zip(keys, values))` is how I would do it too.) – DSM Oct 03 '12 at 20:09
  • @DSM Great point, added to the answer. – phihag Oct 03 '12 at 20:18
1
dict(zip(list1, list2))

is probably the best way to do it. Don't use comprehensions, that's a silly requirement.

Ry-
  • 218,210
  • 55
  • 464
  • 476
0

Well, if you must:

keys = ['one', 'two', 'three']
values = [1,2,3]
d = {a:b for a,b in zip(keys,values)}

But seriously, just use dict(zip(keys, values))

Ben Burns
  • 14,978
  • 4
  • 35
  • 56