Reputation: 11
I have a list of dictionaries. Each dictionary is a different size and can have different and similar key names.
aList = [{
'Hits': 3,
'Blues': 4,
'Classical': 6,
'Metal': 8,
'Rock': 4,
'Funk': 5,
'Hip Hop': 5,
'Rap': 9,
'Easy Listening': 3
}, {
'Rap': 10,
'Jazz': 4,
'Hip Hop': 6,
'Dance': 3,
'Classical': 9,
'Blues': 3,
'Opera': 9,
'Easy Listening': 3,
'Country': 9,
'Pop': 2,
'Hits': 7
}, {
'Blues': 1,
'Metal': 9,
'Hits': 8,
'Dance': 2,
'Funk': 9,
'Jazz': 1,
'Classical': 2
}]
How do I store the sum of all the values corresponding to each key name?
Upvotes: 1
Views: 53
Reputation: 304
Hope this helps you.. Happy coding :)
import pandas as pd
df = pd.DataFrame(columns=['musics','value'])
index=0
for ele in aList:
for i,k in ele.items():
df.loc[index] = [i,k]
index+=1
grped_df = df.groupby('musics').sum().sort_values('musics')
print(grped_df)
Upvotes: 0
Reputation: 144
You definitely need to use built-in Counter
class from collections
module. Here is working code example:
from collections import Counter
aList = [{
'Hits': 3,
'Blues': 4,
'Classical': 6,
'Metal': 8,
'Rock': 4,
'Funk': 5,
'Hip Hop': 5,
'Rap': 9,
'Easy Listening': 3
}, {
'Rap': 10,
'Jazz': 4,
'Hip Hop': 6,
'Dance': 3,
'Classical': 9,
'Blues': 3,
'Opera': 9,
'Easy Listening': 3,
'Country': 9,
'Pop': 2,
'Hits': 7
}, {
'Blues': 1,
'Metal': 9,
'Hits': 8,
'Dance': 2,
'Funk': 9,
'Jazz': 1,
'Classical': 2
}]
counter = Counter()
for d in aList:
counter.update(d)
print(dict(counter))
# Outputs:
# {'Hits': 18, 'Blues': 8, 'Classical': 17, 'Metal': 17, 'Rock': 4, 'Funk': 14, 'Hip Hop': 11, 'Rap': 19, 'Easy Listening': 6, 'Jazz': 5, 'Dance': 5, 'Opera': 9, 'Country': 9, 'Pop': 2}
Upvotes: 2
Reputation: 2436
You can use collections. Counter
from collections import Counter
totals = Counter()
for elem in aList:
totals.update(elem)
print(totals)
Counter({'Rap': 19, 'Hits': 18, 'Classical': 17, 'Metal': 17, 'Funk': 14, 'Hip Hop': 11, 'Opera': 9, 'Country': 9, 'Blues': 8, 'Easy Listening': 6, 'Jazz': 5, 'Dance': 5, 'Rock': 4, 'Pop': 2})
Upvotes: 1