python两个列表的dict合并为⼀个_合并两个dict列表,将值相
加
您需要将输⼊字典转换为(title: count)对,将它们⽤作Counter中的键和值;然后求和后,可以将它们转换回原来的格式:from collections import Counter
summed = sum((Counter({elem['title']: elem['views']}) for elem in a + b), Counter())
c = [{'title': title, 'views': counts} for title, counts in summed.items()]
演⽰:
^{pr2}$
这⾥的⽬标是每个计数都有⼀个唯⼀标识符。如果字典更复杂,则需要将整个字典(减去计数)转换为唯⼀标识符,或者从字典中选择⼀个值作为该标识符。然后将每个标识符的视图计数相加。在
播种作文
从更新的⽰例来看,URL是⼀个很好的标识符。这样你就可以就地收集视图计数了:per_url = {}
for entry in a + b:
key = entry['url']
if key not in per_url:
per_url[key] = py()
el:
per_url[key]['views'] += entry['views']
re前缀的单词
c = per_url.values() # u list(per_url.values()) on Python 3
这只需使⽤字典本⾝(或⾄少第⼀个字典的副本)来计算视图计数:>>> from pprint import pprint
>>> a = [{'title': 'Learning How to Program', 'views': 1,'url': '/4XvR', 'slug': 'learning-how-to-program'},
试用期多久合法... {'title': 'Mastering Programming', 'views': 3,'url': '/7XqR', 'slug': 'mastering-programming'}]
>>> b = [{'title': 'Learning How to Program', 'views': 7,'url': '/4XvR', 'slug': 'learning-how-to-program'},
... {'title': 'Mastering Programming', 'views': 2,'url': '/7XqR', 'slug': 'mastering-programming'},
.
.. {'title': 'Programming Fundamentals', 'views': 1,'url': '/93hB', 'slug': 'programming-fundamentals'}]
>>> per_url = {}
>>> for entry in a + b:
端午的诗... key = entry['url']劳动教育的意义
... if key not in per_url:
... per_url[key] = py()
... el:
... per_url[key]['views'] += entry['views']
...
>>> per_url日常
{'/93hB': {'url': '/93hB', 'title': 'Programming Fundamentals', 'slug': 'programming-fundamentals', 'views': 1}, '/4XvR': {'url':
'/4XvR', 'title': 'Learning How to Program', 'slug': 'learning-how-to-program', 'views': 8}, '/7XqR': {'url': '/7XqR', 'title': 'Mastering Programming', 'slug': 'mastering-programming', 'views': 5}}
>>> pprint(per_url.values())
蒸蛏子[{'slug': 'programming-fundamentals',
'title': 'Programming Fundamentals',
'url': '/93hB',
'views': 1},
萨依巴格乡{'slug': 'learning-how-to-program',
'title': 'Learning How to Program',
'url': '/4XvR',
'views': 8},
{'slug': 'mastering-programming',
'title': 'Mastering Programming',
'url': '/7XqR',
'views': 5}]