List of tuples merging

82 Views Asked by At

I am having trouble with lists of tuples inside them.

If I have a list of tuples like this:

list = [('1', 'a'), ('2', 'b'), ('3', 'c'), ('3', 'd'), ('4', 'e'), ('4', 'f'), ('5', 'g')]

but instead I want to have it formatted like this, where there is only one of each number with a list of letters that are following those numbers instead of them being all separate:

list = [('1', ['a']), ('2', ['b']), ('3', ['c', 'd']), ('4', ['e', 'f']), ('5', ['g'])]

what would be the approach?

3

There are 3 best solutions below

1
Andrej Kesely On BEST ANSWER

Create a grouping dictionary where keys are first values from tuple and values are lists. Then you can convert this dictionary to a final list:

lst = [
    ("1", "a"),
    ("2", "b"),
    ("3", "c"),
    ("3", "d"),
    ("4", "e"),
    ("4", "f"),
    ("5", "g"),
]

out = {}
for a, b in lst:
    out.setdefault(a, []).append(b)

out = list(out.items())
print(out)

Prints:

[('1', ['a']), ('2', ['b']), ('3', ['c', 'd']), ('4', ['e', 'f']), ('5', ['g'])]
0
chepner On

This is the operation done by itertools.groupby. A simple example, given that your list is already properly sorted, looks like

>>> from itertools import groupby
>>> L = [('1', 'a'), ('2', 'b'), ('3', 'c'), ('3', 'd'), ('4', 'e'), ('4', 'f'), ('5', 'g')]
>>> [(k, [x for _, x in v]) for k, v in groupby(L, key=lambda x: x[0])]
[('1', ['a']), ('2', ['b']), ('3', ['c', 'd']), ('4', ['e', 'f']), ('5', ['g'])]

The result of groupby is a mapping of keys (defined by the key argument) to the objects from the list sharing each key. [x for _, x in v] extracts the non-key part of the original tuples.

0
Kanak On

Here's another method of achieving the needed output

lst = [('1', 'a'), ('2', 'b'), ('3', 'c'), ('3', 'd'), ('4', 'e'), ('4', 'f'), ('5', 'g')]

result = {}

for number, letter in lst:
    if number not in result:
        result[number] = [letter]
    else:
        result[number].append(letter)

result_list = list(result.items())

print(result_list)
  1. Creating an empty dictionary(result)
  2. If the number is not already in the dictionary, it initializes an empty list and adds the current letter. If the number is already present, it appends the letter to the existing list.
  3. Finally converting the result dictionary to tuple