我不久前刚刚开始学习Python。
下面是一个例子
我的列表中有一本字典
myword = [{'a': 2},{'b':3},{'c':4},{'a':1}]
我需要将其更改为下面的输出
[{'a':3} , {'b':3} , {'c':4}]
有没有办法可以将这些值加在一起?我尝试使用计数器,但它打印出每个字典。
我使用计数器做了什么:
for i in range(1,4,1):
text = myword[i]
Print Counter(text)
输出
Counter({'a': 2})
Counter({'b': 3})
Counter({'c': 4})
Counter({'a': 1})
我已阅读下面的链接,但他们比较的是两个字典之间的内容。
Is there a better way to compare dictionary values
谢谢!
最佳答案
将字典合并为一个字典(Counter),然后拆分它们。
>>> from collections import Counter
>>> myword = [{'a': 2}, {'b':3}, {'c':4}, {'a':1}]
>>> c = Counter()
>>> for d in myword:
... c.update(d)
...
>>> [{key: value} for key, value in c.items()]
[{'a': 3}, {'c': 4}, {'b': 3}]
>>> [{key: value} for key, value in sorted(c.items())]
[{'a': 3}, {'b': 3}, {'c': 4}]
关于Python 在列表中添加具有相同键的字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27241559/