3

I have two lists of tuples

keys = [(0,1), (2,1)]
values = [('a','b'), ('c','d')]

I want to make a dictionary dict that will apply a function f1 to each

dict.keys[i] = keys[i][0], keys[i][i]: f1(keys[i][0],keys[i][1])

And for the values of the dictionary, I would like to be tuples

dict.values[i] = (f2(values[i][0]), f2(values[i][1]))

What is the most efficient way of doing that in one pass in a pythonic way?

Suever
  • 64,497
  • 14
  • 82
  • 101
curious
  • 1,524
  • 6
  • 21
  • 45

1 Answers1

7

You can do this using a dictionary comprehension.

out = {f1(keys[i][0], keys[i][1]):(f2(values[i][0]),f2(values[i][1])) for i in range(len(keys))}

If you want to avoid using range you can also use zip to accomplish the same thing:

out = {f1(M[0],M[1]):(f2(N[0]), f2(N[1])) for M,N in zip(keys, values)}

And even briefer

out = {f1(*M):tuple(map(f2, N)) for M,N in zip(keys, values)}

If you're on Python 2.6 or earlier (prior to dictionary comprehensions), you can always use a list comprehension and convert to a dictionary explicitly.

out = dict([(f1(*M), tuple(map(f2, N))) for M,N in zip(keys, values)])
Community
  • 1
  • 1
Suever
  • 64,497
  • 14
  • 82
  • 101