Skip to main content
 首页 » 编程设计

python之嵌套字典 : sum values of same key of the dictionaries nested as a value of dictionary

2025年05月04日13davidwang456

我想根据字典 composition 对相同键的值求和:H, C, O, N, S 对于字母组合的字符串输入A、C、D、E。

composition = { 
    'A':  {'H': 5, 'C': 3, 'O': 1, 'N': 1}, 
    'C':  {'H': 5, 'C': 3, 'O': 1, 'N': 1, 'S': 1}, 
    'D':  {'H': 5, 'C': 4, 'O': 3, 'N': 1}, 
    'E':  {'H': 7, 'C': 5, 'O': 3, 'N': 1}, 
} 
 
string_input = ['ACDE', 'CCCDA'] 

预期的结果应该是

out = { 
    'ACDE' : {'H': 22, 'C': 15, 'O': 8, 'N': 4, 'S': 1}, 
    'CCCDA' : {'H': 15, 'C': 9, 'O': 3, 'N': 3, 'S': 3}, 
} 

我正在尝试使用 Counter 但卡在 unsupported operand type(s) for +: 'int' and 'Counter'

from collections import Counter 
 
for each in string_input: 
  out = sum(Counter(composition[aa]) for aa in each) 

请您参考如下方法:

sum() 有一个起始值,从该值开始求和。如果第一个参数中没有要求和的值,这也会提供默认值。该起始值为 0,一个整数。

来自sum() function documentation :

sum(iterable[, start])

Sums start and the items of an iterable from left to right and returns the total. start defaults to 0.

当对 Counter 对象求和时,给它一个空的 Counter() 开始:

sum((Counter(composition[aa]) for aa in each), Counter()) 

如果您随后将结果分配给分配给out 的字典 中的键,您将得到预期结果作为Counter实例:

>>> out = {} 
>>> for each in string_input: 
...     out[each] = sum((Counter(composition[aa]) for aa in each), Counter()) 
... 
>>> out 
{'ACDE': Counter({'H': 22, 'C': 15, 'O': 8, 'N': 4, 'S': 1}), 'CCCDA': Counter({'H': 25, 'C': 16, 'O': 7, 'N': 5, 'S': 3})}