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

Viewed 276

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'],
}

5 Answers

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)

I would do it using map and reduce:

from functools import reduce

reduce(
    lambda d, a: {**d, a[0]: d.get(a[0], []) + [a[1]]},
    map(lambda a: a.split("-"), A),
    {}
)

Explanation

First I split every item by - in A using map.

map(lambda a: a.split("-"), A)

Next, I turn it into a dictionary. The lambda gets the dictionary and the next pair of values. I unpack the dictionary into a new dictionary, then use the first item of the values as key, assign it the current value in the dictionary or an empty array and concatenate it with the current value.

lambda d, a: {**d, a[0]: d.get(a[0], []) + [a[1]]}

You can use collections.defaultdict

from collections import defaultdict
A = ['a-1', 'b-1', 'c-2', 'c-1', 'a-2']
dict3 = defaultdict(list)
for i in A:
    one,two=i.split('-')
    dict3[one].append(two)
print(dict(dict3))

You can also do:

dict1={}
for j in A:
    a,b=j.split('-')
    if a in dict1:
        dict1[a].append(b)
    else:
        dict1[a]=[b]
print(dict1)

The myList, is your list, it will pour it into myDict:

myDict = {}
myList = ['a-1', 'b-1', 'c-2', 'c-1', 'a-2']
for i in myList:
    a, b = i.split('-')
    if a in myDict:
        myDict[a] += [b]
    else:
        myDict[a] = [b]
for j in myDict:
    print(j, ' = ', myDict[j])

it sets i as an object in the list, and then it splits the key and the value by the "-" and if the same key exists, it will add up the value to the list of it, if not, it will make the key and set the value

output:

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

Since you wish for the first element and the last element of the strings to become the keys and values of the output dictionary respectively, you can simply access both using their index Index 0 is first while index -1 is last.

Then create an empty default dictionary with list as the argument Append to the dictionary as shown in the code below

  from collections import *
     A = ['a-1', 'b-1', 'c-2', 'c-1', 'a-2']

     dict = defaultdict(list)
     for l in A:
      p = l[0]
      q = l[-1]
      dict[p].append(q)
      print(dict)
Related