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]
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.
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.
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.
Try this:
dict (zip (list1, list2))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With