2

I am looking for a way to do this in Python without much boiler plate code.

Assume I have a list:

[(a,4),(b,4),(a,5),(b,3)]

I am trying to find a function that will allow me to sort by the first tuple value, and merge the list values together like so:

[(a,[4,3]),(b,[4,5])]

I know I can do this the naive way but I was wondering if there was a better way.

1
  • 3
    how did a 5 turn into a 3 in your output?
    – roippi
    Aug 14, 2013 at 18:13

4 Answers 4

2

Use collections.defaultdict(list):

from collections import defaultdict

lst = [("a",4), ("b",4), ("a",5), ("b",3)]

result = defaultdict(list)
for a, b in lst:
    result[a].append(b)

print sorted(result.items())

# prints: [('a', [4, 5]), ('b', [4, 3])]

Before the sort the algorithm has O(n) complexity; the group by algorithm has O(n * log(n)) and the set/list/dict comprehension has something greater than O(n^2)

3
0

Assuming that 'a' is your initial list an 'b' is the expected result, the following code will work:

d = {}
for k, v in a:
    if k in d:
        d[k].append(v)
    else:
        d[k] = [v] 
b = d.items()
2
  • this is the naive solution I wrote Aug 14, 2013 at 18:31
  • This is another option [(key,[v2 for k2, v2 in a if k2 == key ]) for key in list(set(map(lambda x: x[0], a)))] Aug 14, 2013 at 18:48
0

Not so efficient, but enough (with set + list + dict comprehension):

>>> data = [("a",4), ("b",4), ("a",5), ("b",3)]
>>> {key: [v for k, v in data if k == key]
...  for key in {k for k, v in data}
... }.items()
[('a', [4, 5]), ('b', [4, 3])]
3
  • I am sure this is good but a nightmare to read, I want people at any level of python to read it. Aug 14, 2013 at 18:31
  • This is nowhere good, but it is a way to do it without using any statements :D Aug 14, 2013 at 18:34
  • It's really not efficient but I still think this is the easiest to understand.
    – H.D.
    Aug 29, 2013 at 22:17
0

Another option (again assuming 'a' is the initial list)

[(key,[v2 for k2, v2 in a if k2 == key ]) for key in list(set(map(lambda x: x[0], a)))]
1
  • The casting to list isn't needed, as the set is already an iterable.
    – H.D.
    Aug 29, 2013 at 22:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.