8

Is it possible to combine two list as a key value pair. The number of elements in both lists are same.

i have two lists as follows.

list1 = ["a","b","c","d","e"]
list2 = ["1","2","3","4","5"]

How i cam combine like the following

dict['a':1,'b':2,'c':3,'d':4,'e':5]
Volatility
  • 31,232
  • 10
  • 80
  • 89
just_in
  • 437
  • 3
  • 6
  • 10

3 Answers3

17

dictA = dict(zip(list1, list2))

More info on the zip function is available here: http://docs.python.org/2/library/functions.html#zip

The above line first evaluates the zip(list1, list2), which creates a list containing n tuples out of the nth element of the two lists. The dict call then takes the list of tuples and creates keys out of the first value in the tuple, with the value of the respective key being the second value.

John Brodie
  • 5,909
  • 1
  • 19
  • 29
  • This is working, but the problem is it is not one to one mapping. i tried dict(zip(list1, map(list2))) also – just_in Feb 02 '13 at 04:44
  • Isn't this what you want? In [1]: list1 = ["a","b","c","d","e"] In [2]: list2 = ["1","2","3","4","5"] In [3]: dicta = dict(zip(list1, list2)) In [4]: print dicta {'a': '1', 'c': '3', 'b': '2', 'e': '5', 'd': '4'} – John Brodie Feb 02 '13 at 04:45
3

Try this:

dict (zip (list1, list2))
Hyperboreus
  • 31,997
  • 9
  • 47
  • 87
2

Do this:

my_dict = dict(zip(list1, map(int, list2)))

Or with a dict comprehension:

my_dict = {k: int(v) for k, v in zip(list1, list2)}
  • map maps a function to each element of an iterable.

    map(int, list2) == [1, 2, 3, 4, 5]
    
  • zip gives a list of tuples of the nth element of each of the lists. However if the list lengths aren't the same, it goes up to the length of the shortest list.

    zip('foo', '1234') == [('f', '1'), ('o', '2'), ('o', '3')]
    
Volatility
  • 31,232
  • 10
  • 80
  • 89