Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I combine two lists into a dictionary in Python? [duplicate]

I have two lists of the same length:

[1,2,3,4] and [a,b,c,d]

I want to create a dictionary where I have {1:a, 2:b, 3:c, 4:d}

What's the best way to do this?

like image 221
SuperString Avatar asked Sep 01 '11 13:09

SuperString


People also ask

Can we add duplicate values in dictionary Python?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.

Can we add duplicate values in dictionary?

[C#] Dictionary with duplicate keys The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.

How do you merge two lists in Python?

In python, we can use the + operator to merge the contents of two lists into a new list. For example, We can use + operator to merge two lists i.e. It returned a new concatenated lists, which contains the contents of both list_1 and list_2.


2 Answers

dict(zip([1,2,3,4], [a,b,c,d])) 

If the lists are big you should use itertools.izip.

If you have more keys than values, and you want to fill in values for the extra keys, you can use itertools.izip_longest.

Here, a, b, c, and d are variables -- it will work fine (so long as they are defined), but you probably meant ['a','b','c','d'] if you want them as strings.

zip takes the first item from each iterable and makes a tuple, then the second item from each, etc. etc.

dict can take an iterable of iterables, where each inner iterable has two items -- it then uses the first as the key and the second as the value for each item.

like image 113
agf Avatar answered Sep 23 '22 02:09

agf


>>> dict(zip([1, 2, 3, 4], ['a', 'b', 'c', 'd'])) {1: 'a', 2: 'b', 3: 'c', 4: 'd'} 

If they are not the same size, zip will truncate the longer one.

like image 34
Josh Lee Avatar answered Sep 26 '22 02:09

Josh Lee