Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I take two tuples to produce a dictionary? [duplicate]

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 }
like image 635
Jamie Avatar asked Jun 22 '17 18:06

Jamie


People also ask

How do you turn two tuples into a dictionary?

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.

Can you have duplicates in a 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.

Can there be duplicate in dictionary python?

Python dictionary doesn't allow key to be repeated.


2 Answers

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.

like image 109
Willem Van Onsem Avatar answered Sep 19 '22 17:09

Willem Van Onsem


You can use a dictionary comprehension:

>>> {y[i]:x[i] for i,_ in enumerate(x)}
{'a': 1, 'b': 2, 'c': 3}
like image 38
Emilio M Bumachar Avatar answered Sep 20 '22 17:09

Emilio M Bumachar