My first thought is to write an interator, or maybe do some list comprehension. But, like every 5-10 line method I write in python, someone can usually point me to a call in the standard library to accomplish the same.
How can I go from two tuples, x
and y
to a dictionary z
?
x = ( 1, 2, 3 )
y = ( 'a', 'b', 'c')
z = { }
for index, value in enumerate(y):
z[value] = x[index]
print z
# { 'a':1, 'b':2, 'c':3 }
Method #2 : Using zip() + dict() The zip function is responsible for conversion of tuple to key-value pair with corresponding indices. The dict function performs the task of conversion to dictionary.
Duplicate keys are not allowed. A dictionary maps each key to a corresponding value, so it doesn't make sense to map a particular key more than once. If you specify a key a second time during the initial creation of a dictionary, then the second occurrence will override the first.
Python dictionary doesn't allow key to be repeated.
Tuples are iterables. You can use zip
to merge two or more iterables into tuples of two or more elements.
A dictionary can be constructed out of an iterable of 2-tuples, so:
# v values
dict(zip(y,x))
# ^ keys
This generates:
>>> dict(zip(y,x))
{'c': 3, 'a': 1, 'b': 2}
Note that if the two iterables have a different length, then zip
will stop from the moment one of the tuples is exhausted.
You can - as @Wondercricket says - use izip_longest
(or zip_longest
in python-3.x) with a fillvalue
: a value that is used when one of the iterables is exhausted:
from itertools import izip_longest
dict(izip_longest(y,x,fillvalue=''))
So if the key iterable gets exhausted first, all the remaining values will be mapped on the empty string here (so only the last one will be stored). If the value iterable is exhausted first, all remaining keys will here be mapped on the empty string.
You can use a dictionary comprehension:
>>> {y[i]:x[i] for i,_ in enumerate(x)}
{'a': 1, 'b': 2, 'c': 3}
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