Skip to main content
 首页 » 编程设计

Python 在列表中添加具有相同键的字典值

2024年10月25日11hnrainll

我不久前才开始学习 python。

下面的例子

我在列表中有一个字典

myword = [{'a': 2},{'b':3},{'c':4},{'a':1}] 

我需要把它改成下面的输出

[{'a':3} , {'b':3} , {'c':4}] 

有什么方法可以将值(value)加在一起吗?我尝试使用计数器,但它会打印出每个字典。

我使用 Counter 做了什么:

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

我已经阅读了下面的链接,但他们比较的是 2 dict。

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