Python. converting 2 lists into one dictionary object

11,059

Solution 1

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)}

Solution 2

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)}

Solution 3

dict(zip(list1, list2))

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

Share:
11,059

Related videos on Youtube

Fred4106
Author by

Fred4106

Updated on June 04, 2022

Comments

  • Fred4106
    Fred4106 almost 2 years

    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.

    • Ben Burns
      Ben Burns over 11 years
      Why do you have to use comprehension?
    • abarnert
      abarnert over 11 years
      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.
  • DSM
    DSM over 11 years
    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.)
  • phihag
    phihag over 11 years
    @DSM Great point, added to the answer.
  • root
    root over 11 years
    @ user1718234 -- You are welcome. If it was helpful you should accept the answer.