Reputation: 12417
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!
Upvotes: 3
Views: 79
Reputation: 73450
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()}
Upvotes: 6
Reputation: 71570
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())))
Upvotes: 0
Reputation: 20414
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)}
Upvotes: 3
Reputation: 43136
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)}
Upvotes: 3