2014-12-02 233 views
1

我刚刚拿起了不久前的Python。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}) 

我已阅读下面的链接,但在2字典之间他们进行比较。

Is there a better way to compare dictionary values

谢谢!

回答

1

将字典合并到一个字典(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}] 
+0

简单而不错。谢谢! – NitroReload 2014-12-02 04:12:42

相关问题