从字典中汇总值(Python方式)

nev*_*int 2 python dictionary

鉴于以下字典,我们称之为 mydict

 {'Plekhg2': {'Bcells': '233.55', 'DendriticCells': '190.12'}, 
  'Barxxxx': {'Bcells': '132.11', 'DendriticCells': '92.01'}, }
Run Code Online (Sandbox Code Playgroud)

我想从内部字典中总结每个键的值,结果是:

 {'Plekhg2': 423.67,  # 233.55 + 190.12
  'Barxxxx': 224.12}  # 132.11 + 92.01
Run Code Online (Sandbox Code Playgroud)

我怎样才能用Python成语实现这一目标?

Mar*_*ers 5

使用dict理解,使用sum()对嵌套字典值求和; Python 2.6或之前将使用dict()和生成器表达式:

# Python 2.7
{k: sum(float(f) for f in v.itervalues()) for k, v in mydict.iteritems()}
# Python 3.x
{k: sum(map(float, v.values())) for k, v in mydict.items()}
# Python 2.6 and before
dict((k, sum(float(f) for f in v.values())) for k, v in mydict.iteritems())
Run Code Online (Sandbox Code Playgroud)

尽管如此,您可能希望存储浮点值.

演示:

>>> mydict ={'Plekhg2': {'Bcells': '233.55', 'DendriticCells': '190.12'}, 
...   'Barxxxx': {'Bcells': '132.11', 'DendriticCells': '92.01'}, }
>>> {k: sum(float(f) for f in v.itervalues()) for k, v in mydict.iteritems()}
{'Plekhg2': 423.67, 'Barxxxx': 224.12}
Run Code Online (Sandbox Code Playgroud)