Convert dictionary with tuples as keys to tuples that contain keys and value

Viewed 66

I have a dictionary like this:

d = {('a','b','c'):4, ('e','f','g'):6}

and I would like to have a set of tuples like this:

{('a', 'b', 'c', 4), ('e', 'f', 'g', 6)}

I've tried in this way:

b = set(zip(d.keys(), d.values()))

But the output is this:

set([(('a', 'b', 'c'), 4), (('e', 'f', 'g'), 6)])

How can i solve that? Thanks!

4 Answers

In Python >= 3.5, you can use generalized unpacking in this set comprehension:

{(*k, v) for k, v in d.items()}
# {('a', 'b', 'c', 4), ('e', 'f', 'g', 6)}

But the more universally applicable tuple concatenation approach as suggested by Aran-Fey is not significantly more verbose:

{k + (v,) for k, v in d.items()}

You don't want to zip the keys with the values, you want to concatenate them:

>>> {k + (v,) for k, v in d.items()}
{('a', 'b', 'c', 4), ('e', 'f', 'g', 6)}

Use a set comprehension to iterate over the key, value pairs, and then create new tuples from the exploded (unpacked) key and the value:

>>> {(*k, v) for k, v in d.items()}
{('e', 'f', 'g', 6), ('a', 'b', 'c', 4)}

Or try map:

print(set(map(lambda k: k[0]+(k[1],),d.items())))

Or (python 3.5 up):

print(set(map(lambda k: (*k[0],k[1]),d.items())))
Related