Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to merge 2 list as a key value pair in python [duplicate]

Tags:

python

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]
like image 326
just_in Avatar asked Feb 02 '13 04:02

just_in


People also ask

How do I combine two values in a list Python?

One simple and popular way to merge(join) two lists in Python is using the in-built append() method of python. The append() method in python adds a single item to the existing list. It doesn't return a new list of items. Instead, it modifies the original list by adding the item to the end of the list.

How do you combine keys and values in Python?

Method #1 : Using zip() + loop + defaultdict() The combination of above method can be used to perform this particular task. In this, we use zip function to match the like elements of lists with each other and loop is then used to assign the keys with value from zipped list to add value to a defaultdict.


2 Answers

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.

like image 171
John Brodie Avatar answered Oct 28 '22 19:10

John Brodie


Try this:

dict (zip (list1, list2))
like image 39
Hyperboreus Avatar answered Oct 28 '22 20:10

Hyperboreus