根据其他键

时间:2017-09-10 12:12:19

标签: python dictionary sum

所以我有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}]

1 个答案:

答案 0 :(得分:1)

在一行中,使用itertools.groupby,词典&列表理解

  • 按照word
  • 的值对dicts进行分组
  • 使用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}]