Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 总结字典的价值_Python_Python 3.x_Dictionary - Fatal编程技术网

Python 总结字典的价值

Python 总结字典的价值,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我有一本字典,如下所示: grocery={ 'James': {'Brocolli': 3, 'Carrot': 3, 'Cherry': 5}, 'Jill': {'Apples': 2, 'Carrot': 4, 'Tomatoes': 8}, 'Sunny': {'Apples': 5, 'Carrot': 2, 'Cherry': 2, 'Chicken': 3, 'Tomatoes': 6} } food={} for a,b in grocery.items

我有一本字典,如下所示:

grocery={
    'James': {'Brocolli': 3, 'Carrot': 3, 'Cherry': 5},
    'Jill': {'Apples': 2, 'Carrot': 4, 'Tomatoes': 8},
    'Sunny': {'Apples': 5, 'Carrot': 2, 'Cherry': 2, 'Chicken': 3, 'Tomatoes': 6}
}
food={}
for a,b in grocery.items():
     for i,j in b.items():
          food[i]+=(b.get(i,0))
我正试图计算每种食物的总数,但它并没有按预期的那样工作

例如:我想数一数胡萝卜的总数,苹果的总数等等

上面的代码给了我以下错误:

File "dictionary1.py", line 6, in <module>
      food[i]+=(b.get(i,0))
   KeyError: 'Cherry
文件“dictionary1.py”,第6行,在
食物[i]+=(b.get(i,0))
关键错误:“Cherry

如何总结每一项的总数?

你的
食品
字典是空的,一开始没有键;你不能仅仅把一个价值总结成一个还不存在的东西

再次使用
dict.get()
获取当前值或默认值,而不是
+=

food[i] = food.get(i, 0) + b.get(i,0)
您实际上不需要在此处使用
b.get()
,因为变量
j
中已有
b
的值:

food[i] = food.get(i, 0) + j
您还可以在尝试访问密钥时使用默认值使密钥“自动”存在:

from collections import defaultdict

food = defaultdict(int)  # insert int() == 0 when a key is not there yet
然后在内部循环中使用
食物[i]+=j

我强烈建议您对变量使用更好的名称。如果迭代
dict.values()
而不是
dict.items()
,则只有在不需要键的情况下才可以查看值(如外部
for
循环):

另一种选择是使用专用的计数和求和字典子类,称为。此类直接支持将您的食品杂货汇总到一行:

from collections import Counter

food = sum(map(Counter, grocery.values()), Counter())
map(Counter,…)
为每个输入字典创建
Counter
对象,并且
sum()
将所有这些对象相加(额外的
Counter()
参数“prime”函数使用空的
Counter()
作为起始值,而不是整数
0

后者的演示:

>>> from collections import Counter
>>> sum(map(Counter, grocery.values()), Counter())
Counter({'Tomatoes': 14, 'Carrot': 9, 'Cherry': 7, 'Apples': 7, 'Brocolli': 3, 'Chicken': 3})
计数器仍然是一个字典,只是一个具有额外功能的字典。通过将
计数器
传递到
dict()
,您始终可以返回字典:


你的
食物
字典是空的,一开始没有钥匙;你不能仅仅把一个价值总结成一个还不存在的东西

再次使用
dict.get()
获取当前值或默认值,而不是
+=

food[i] = food.get(i, 0) + b.get(i,0)
您实际上不需要在此处使用
b.get()
,因为变量
j
中已有
b
的值:

food[i] = food.get(i, 0) + j
您还可以在尝试访问密钥时使用默认值使密钥“自动”存在:

from collections import defaultdict

food = defaultdict(int)  # insert int() == 0 when a key is not there yet
然后在内部循环中使用
食物[i]+=j

我强烈建议您对变量使用更好的名称。如果迭代
dict.values()
而不是
dict.items()
,则只有在不需要键的情况下才可以查看值(如外部
for
循环):

另一种选择是使用专用的计数和求和字典子类,称为。此类直接支持将您的食品杂货汇总到一行:

from collections import Counter

food = sum(map(Counter, grocery.values()), Counter())
map(Counter,…)
为每个输入字典创建
Counter
对象,并且
sum()
将所有这些对象相加(额外的
Counter()
参数“prime”函数使用空的
Counter()
作为起始值,而不是整数
0

后者的演示:

>>> from collections import Counter
>>> sum(map(Counter, grocery.values()), Counter())
Counter({'Tomatoes': 14, 'Carrot': 9, 'Cherry': 7, 'Apples': 7, 'Brocolli': 3, 'Chicken': 3})
计数器仍然是一个字典,只是一个具有额外功能的字典。通过将
计数器
传递到
dict()
,您始终可以返回字典:


你会得到这个错误,因为在开始的时候,键,即“苹果”,“西红柿”,不存在于食物中。您可以使用try-Exception块更正此问题:

grocery={
    "Jill":{"Apples":2, "Tomatoes":8,"Carrot":4},
    "James":{"Carrot":3,"Brocolli":3,"Cherry":5},
    "Sunny":{"Chicken":3,"Apples":5,"Carrot":2,"Tomatoes":6,"Cherry":2}
}
food={}
for a,b in grocery.items():
    for i,j in b.items():
        try:
            food[i] += j
        except KeyError:
            food[i] = j

另外,您可以去掉b.get(i,0)语句,因为您已经在b中进行了迭代,只得到了b中实际存在的值(j)。

您会得到错误,因为在开始时,键,即“苹果”、“西红柿”在食物中不存在。您可以使用try-Exception块更正此问题:

grocery={
    "Jill":{"Apples":2, "Tomatoes":8,"Carrot":4},
    "James":{"Carrot":3,"Brocolli":3,"Cherry":5},
    "Sunny":{"Chicken":3,"Apples":5,"Carrot":2,"Tomatoes":6,"Cherry":2}
}
food={}
for a,b in grocery.items():
    for i,j in b.items():
        try:
            food[i] += j
        except KeyError:
            food[i] = j
此外,您还可以去掉b.get(i,0)语句,因为您已经在b中进行了迭代,并且只获取b中实际存在的值(j)。

只需这样做即可

从集合导入defaultdict

food=defaultdict(int)
只需执行

从集合导入defaultdict


food=defaultdict(int)
你不能使用
+=
,你需要
food[i]=food.get(i,0)+j
你不能使用
+=
,你需要
food[i]=food.get(i,0)+j