2017-09-10 53 views
1

相似所以我這一下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
在一行

,使用itertools.groupby,字典&列表理解

  • 組通過的word
  • 值的類型的字典重建使用likes值的總和和word密鑰的值的類型的字典,在列表理解

代碼使用字典理解:

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