1

I have a tuple that contains multiple sub tuples, with a fixed length of two and each sub tuple has two string values.

NOTE: The length and value type of these sub tuples never change.

I'd like to use the sub tuples in a dictionary-comprehension, like this:

{sub_tuple for sub_tuple in main_tuple}

The problem is, I get:

{(w, x), (y, z)}

Instead of:

{w: x, y: z}

How can I get this to work without creating any additional variables?

For example, how do I avoid doing something like this:

x = {}
for sub_tuple in main_tuple:
  x[sub_tuple[0]] = sub_tuple[1]
# do whatever with x...
piet.t
  • 11,718
  • 21
  • 43
  • 52
Malekai
  • 4,765
  • 5
  • 25
  • 60
  • The dupe "reverses" the order - but you should be able to derive your solution from it as well. Those answers duplicate the ones give here "with an added twist". – Patrick Artner Mar 23 '19 at 13:29

2 Answers2

3

You should be able to do:

x = {
    key: value
    for key, value in main_tuple
}

Even simpler, you could do x = dict(main_tuple)

schillingt
  • 13,493
  • 2
  • 32
  • 34
3

You can use the dict constructor instead:

dict(main_tuple)
blhsing
  • 91,368
  • 6
  • 71
  • 106