我有以下字典,即从XHR请求生成的json对象,其中字典键由元组组成:
{(u'goal', u'corner', u'rightfoot'): 1, (u'goal', u'openplay', u'rightfoot'): 3, (u'miss',
u'corner', u'header'): 8, (u'goal', u'corner', u'header'): 1, (u'goal', u'openplay', u'leftfoot'): 2,
(u'miss', u'openplay', u'rightfoot'): 30, (u'miss', u'corner', u'rightfoot'): 2, (u'miss',
u'crossedfreekick', u'header'): 3, (u'goal', u'penalty', u'rightfoot'): 1, (u'miss', u'fastbreak',
u'rightfoot'): 2, (u'miss', u'crossedfreekick', u'rightfoot'): 3, (u'goal', u'openplay', u'header'):
1, (u'goal', u'crossedfreekick', u'rightfoot'): 1, (u'miss', u'openplay', u'header'): 2, (u'goal',
u'crossedfreekick', u'header'): 1, (u'miss', u'openplay', u'leftfoot'): 22, (u'miss',
u'directfreekick', u'rightfoot'): 1, (u'miss', u'crossedfreekick', u'leftfoot'): 1}
我使用以下代码来有条理地对上面的字典中的值求和:
goal1 = {"'goal','openplay','leftfoot'", "'goal','openplay','rightfoot'", "'goal','openplay','header'", "'goal','openplay','otherbodypart'"}
regex1 = sum(int(value) for key, value in regex if key in goal1)
但是,这会产生以下错误消息:
regex1 = sum(int(value) for key, value in regex if key in goal1)
exceptions.ValueError: too many values to unpack
任何人都可以向我解释为什么这是和/或更正另一种语法?
由于
答案 0 :(得分:2)
regex1 = sum(int(value) for key, value in regex.items() if key in goal1)
你需要使用包含键和值的dict.items
,循环遍历regex
dict,你只是在迭代密钥,因此你无法解包密钥和值,因此错误。< / p>
键也是元组,因此您需要将键存储为goal1
中的元组:
goal1 = {('goal','openplay','leftfoot'), ('goal','openplay','rightfoot'), ('goal','openplay','header'), ('goal','openplay','otherbodypart')}
print(regex1)
6