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?
The straight answer is NO. You can not have duplicate keys in a dictionary in Python.
[C#] Dictionary with duplicate keys The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.
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.
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.
>>> 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.
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