所以我有python词典列表,如下所示:
[{"word": 'app idea', "post" : 'i just had an app idea', "likes" : 22},
{"word": 'app idea', "post" : 'this is a great app idea', "likes" : 29},
{"word": 'app development', "post" : 'let us start our app development', "likes" : 32},
{"word": 'app development', "post" : 'app development will take time', "likes" : 23},
{"word": 'app data', "post" : 'delete the app data', "likes" : 32}]
我想添加单词相同的喜欢
所以最终输出看起来像这样
[{"word": 'app idea', "likes" : 51},
{"word": 'app development', "likes" : 55},
{"word": 'app data', "likes" : 32}]
答案 0 :(得分:1)
在一行中,使用itertools.groupby
,词典&列表理解
word
键likes
值的总和和word
键的值重建dicts,使用列表理解中的dict理解代码:
list_of_dicts = [{"word": 'app idea', "post" : 'i just had an app idea', "likes" : 22},
{"word": 'app idea', "post" : 'this is a great app idea', "likes" : 29},
{"word": 'app development', "post" : 'let us start our app development', "likes" : 32},
{"word": 'app development', "post" : 'app development will take time', "likes" : 23},
{"word": 'app data', "post" : 'delete the app data', "likes" : 32}]
import itertools
result = [{"word":k,"likes":sum(v["likes"] for v in vl)} for k,vl in itertools.groupby(list_of_dicts,key=lambda k : k["word"])]
结果:
[{'word': 'app idea', 'likes': 51}, {'word': 'app development', 'likes': 55}, {'word': 'app data', 'likes': 32}]