嵌套字典:嵌套为字典值的字典的相同键的值

时间:2017-12-06 08:07:20

标签: python python-2.7 dictionary

我想根据字典H, C, O, N, S对字符composition的值进行求和,字符串输入是字母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)

2 个答案:

答案 0 :(得分:5)

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

来自sum() function documentation

  

sum(iterable[, start])

     

从左到右汇总开始 iterable 的项目并返回总计。 开始默认为0

汇总Counter个对象时,请先为空Counter()开头:

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

如果您将结果分配给分配给out词典中的,则会得到Counter个实例的预期结果:< / p>

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

答案 1 :(得分:0)

三个嵌套for循环应该可以完成工作。

out = {}
for x in string_input: # for each string in list
    current = out[x] = {}
    for char in x: # for each character in the string
        cur_composition=composition[char]
        for val in cur_composition: # for all the entry in the composition dictionary for that character
            current[char]= cur_composition[val] if val not in current[char] else cur_composition[val]+current[char]