Search code examples
pythondictionarydata-structuresaggregatedata-analysis

How to aggregate data from a python list to a dictionary?


I have a list:

A = ['a-1', 'b-1', 'c-2', 'c-1', 'a-2']

What is the pythonic way (I don't want to use lots of nested for loops) of aggregating the data in a dictionary (or any other data structure) to get a result like:


{
'a': ['1', '2'],
'b': ['1'],
'c': ['1', '2'],
}


Solution

  • IIUC, here's one way:

    from collections import defaultdict
    
    result = defaultdict(list)
    for i in A:
        a, b = i.split('-')
        result[a].append(b)
    

    OUTPUT:

    defaultdict(list, {'a': ['1', '2'], 'b': ['1'], 'c': ['2', '1']})
    

    NOTE: you can also use setdefault :

    result = {}
    for i in A:
        a, b = i.split('-')
        result.setdefault(a, []).append(b)