23

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 }
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Jamie
  • 7,075
  • 12
  • 56
  • 86

2 Answers2

38

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 ) 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.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
6

You can use a dictionary comprehension:

>>> {y[i]:x[i] for i,_ in enumerate(x)}
{'a': 1, 'b': 2, 'c': 3}
Emilio M Bumachar
  • 2,532
  • 3
  • 26
  • 30
  • What will this do if `x` is longer than `y`? Exactly, `IndexError`. – Mast Jun 22 '17 at 20:17
  • 1
    If you expect x and y to be the same length, the zip approach will also not give you what you want (it'll silently produce unexpected results, instead of an error). This approach is much simpler imo, and you'll probably need to handle different-length key/value lists explicitly regardless. – mfsiega Jun 22 '17 at 20:54
  • (Though, once you know the idiom that "zip means make a dictionary", I guess it's equally readable.) – mfsiega Jun 22 '17 at 20:55