Search code examples
pythonlisttuples

List of tuples merging


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?


Solution

  • 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'])]