python - Adding values of a key, based on the similarity of other key -
so have list of python dictionary this:
[{"word": 'app idea', "post" : 'i had app idea', "likes" : 22}, {"word": 'app idea', "post" : 'this great app idea', "likes" : 29}, {"word": 'app development', "post" : 'let start our app development', "likes" : 32}, {"word": 'app development', "post" : 'app development take time', "likes" : 23}, {"word": 'app data', "post" : 'delete app data', "likes" : 32}]
i want add likes word same
so final output looks this
[{"word": 'app idea', "likes" : 51}, {"word": 'app development', "likes" : 55}, {"word": 'app data', "likes" : 32}]
in 1 line, using itertools.groupby
, dictionary & list comprehension
- group dicts value of
word
key - rebuild dicts using sum of
likes
values , value ofword
key, using dict comprehension in list comprehension
code:
list_of_dicts = [{"word": 'app idea', "post" : 'i had app idea', "likes" : 22}, {"word": 'app idea', "post" : 'this great app idea', "likes" : 29}, {"word": 'app development', "post" : 'let start our app development', "likes" : 32}, {"word": 'app development', "post" : 'app development take time', "likes" : 23}, {"word": 'app data', "post" : 'delete app data', "likes" : 32}] import itertools result = [{"word":k,"likes":sum(v["likes"] v in vl)} k,vl in itertools.groupby(list_of_dicts,key=lambda k : k["word"])]
result:
[{'word': 'app idea', 'likes': 51}, {'word': 'app development', 'likes': 55}, {'word': 'app data', 'likes': 32}]
Comments
Post a Comment