Search code examples
pythonlistdictionarytuplesgenerator

Consolidating tuples as a dict based on condition


input :

x = ( (1,"A", 10),(1,"B", 10),(1,"B", 10),(1,"C", 10),(1,"C", 10),(1,"B", 10),(1,"A", 10),(1,"A", 10),(1,"C", 10),(1,"B", 10))

Expected Output:

{'A': [(1, 'A', 10), (7, 'A', 70), (8, 'A', 80)], 'B': [(2, 'B', 20), (3, 'B', 30), (6, 'B', 60), (10, 'B', 100)], 'C': [(4, 'C', 40), (5, 'C', 50), (9, 'C', 90)]}

Basically grouping my tuples by one of the elements in the tuple

I tried this, but it doesn't feel Pythonic

def consolidate(values):
    res = {}
    for a in values:
        if a[1] in res:
            p = res[a[1]]
            p.append(a)
            res[a[1]] = p
        else:
            res[a[1]] = [a]
    return res

Solution

  • You can use dict.setdefault:

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

    Prints:

    {
        "A": [(1, "A", 10), (1, "A", 10), (1, "A", 10)],
        "B": [(1, "B", 10), (1, "B", 10), (1, "B", 10), (1, "B", 10)],
        "C": [(1, "C", 10), (1, "C", 10), (1, "C", 10)],
    }