Given a list of tuples like so:
a = [ ( "x", 1, ), ( "x", 2, ), ( "y", 1, ), ( "y", 3, ), ( "y", 4, ) ]
What would be the easiest way to filter for unique first element and merge the second element. An output like so would be desired.
b = [ ( "x", 1, 2 ), ( "y", 1, 3, 4 ) ]
Thanks,
>>> a = [("x", 1,), ("x", 2,), ("y", 1,), ("y", 3,), ("y", 4,)]
>>> d = {}
>>> for k, v in a:
... d.setdefault(k, [k]).append(v)
>>> b = map(tuple, d.values())
>>> b
[('y', 1, 3, 4), ('x', 1, 2)]
You can use a defaultdict
:
>>> from collections import defaultdict
>>> d = defaultdict(tuple)
>>> a = [('x', 1), ('x', 2), ('y', 1), ('y', 3), ('y', 4)]
>>> for tup in a:
... d[tup[0]] += (tup[1],)
...
>>> [tuple(x for y in i for x in y) for i in d.items()]
[('y', 1, 3, 4), ('x', 1, 2)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With