Marco Fernandes
Marco Fernandes

Reputation: 336

How to group tuples in a list with multiple values matching

I want to group a list of tuples with multiple common values as efficiently as possible. I know the long method of doing it but wondering what a quicker more "Pythonic" way of doing it would be.

What I'm trying to achieve:

lst = [('a', '1', 1),
       ('a', '1', 2),
       ('a', '2', 2),
       ('b', '1', 1),
       ('c', '1', 1)]

result = [
        [('a', '1', 1), ('a', '1', 2)],
        [('a', '2', 1)],
        [('b', '1', 1)]
        [('c', '1', 1)]
    ]

ideally the true result I'd like to get to would be:

result = [
        [('a', '1', 1), ('a', '1', 2)],
    ]

where if there is no matching pairs then it excludes them but I think I can do that with set()

Upvotes: 1

Views: 176

Answers (1)

Rakesh
Rakesh

Reputation: 82805

Using dict.setdefault

Ex:

r = {}
for i in lst:
    r.setdefault((i[0], i[1]), []).append(i)   #key -> First 2 values

print(list(r.values()))
#OR print([i for i in r.values() if len(i) > 1])

Output:

[[('a', '1', 1), ('a', '1', 2)],
 [('a', '2', 2)],
 [('b', '1', 1)],
 [('c', '1', 1)]]

Upvotes: 1

Related Questions