2016-11-12 63 views
0

我已经一个字典结构类似于[A] [B] =(C),例如:使用二级密钥总结字典值

{'cat': {1:1, 2:3, 3:1, 4:1}, 'dog': {1:8, 2:2, 3:4}, 'egg': {5:1, 6:2}, 'frog': {2:1, 4:1, 5:1}, 'nuts': {3:1}, 'idea': {4:1}} 

我想什么能够做的是搜索由[b]键并对相应的c进行求和。所以我会得到以下输出:

1:9,2:6,3:6 ...等等。

这是否需要重组字典?

回答

2

,您可以在其上类型的字典和总结值使用collections.defaultdict每个键的字典中的值进行迭代。然后,你只需访问结果字典找出加值为每个键,无需搜索:

from collections import defaultdict 

d = {'cat': {1:1, 2:3, 3:1, 4:1}, 'dog': {1:8, 2:2, 3:4}, 'egg': {5:1, 6:2}, 'frog': {2:1, 4:1, 5:1}, 'nuts': {3:1}, 'idea': {4:1}} 

result = defaultdict(int) 
for i in d.values(): 
    for j in i: 
     result[j] += i[j] 

print(result) 
# defaultdict(<class 'int'>, {1: 9, 2: 6, 3: 6, 4: 3, 5: 2, 6: 2}) 

>>> print(result[1]) 
9 
+0

您也可以使用['collections.Counter'](https://docs.python.org/2/library /collections.html#collections.Counter),默认情况下已从零开始提供数字值。 –

0

我假设你有这样的解释:

d = {'cat': {1:1, 2:3, 3:1, 4:1}, 'dog': {1:8, 2:2, 3:4}, 'egg': {5:1, 6:2}, 'frog': {2:1, 4:1, 5:1}, 'nuts': {3:1}, 'idea': {4:1}}} 

现在我们来写这将需要一个参数(整数),总结所有值在所有内部字典这个整数的函数。

def calc(b): 
    result = 0 
    for val in d.values(): 
     if b in val: 
      result += val[b] 
0

如果你需要的是总的,那么你可以sum了所有使用值:

>>> b = 2 
>>> sum(a.get(b, 0) for a in d.values()) 
6 

如果你想把所有的b s然后使用collections.Counter()其行为类似于dict做所有的繁重:

>>> from collections import Counter 
>>> sum((Counter(a) for a in d.values()), Counter()) 
Counter({1: 9, 2: 6, 3: 6, 4: 3, 5: 2, 6: 2}) 

但是,如果你真的很挑剔并希望dict

>>> dict(sum((Counter(a) for a in d.values()), Counter())) 
{1: 9, 2: 6, 3: 6, 4: 3, 5: 2, 6: 2} 
+0

答案应该是一本字典。 –