python - 为什么我收到错误 'exceptions.ValueError: too many values to unpack' ?

标签 python json dictionary

我有以下字典,它是从 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

任何人都可以向我解释为什么这是和/或更正替代语法吗?

谢谢

最佳答案

regex1 = sum(int(value) for key, value in regex.items() if key in goal1)

您需要使用包含键和值的dict.items,循环遍历您仅迭代键的regex字典,这样您就无法解压键以及由此产生的错误值。

键也是元组,因此您需要将键作为元组存储在goal1中:

goal1 = {('goal','openplay','leftfoot'), ('goal','openplay','rightfoot'), ('goal','openplay','header'), ('goal','openplay','otherbodypart')}


print(regex1)
6

关于python - 为什么我收到错误 'exceptions.ValueError: too many values to unpack' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26445190/

相关文章:

javascript - 如何用javascript浏览json内容?

python - 带有 Elasticsearch 的 python 中的 "exceptions.TypeError: list indices must be integers not str"

Python 按阈值将字典拆分为更小的字典

c# - 从 xml 创建字典

python - 如何在不必编写 20 个 if 语句或制作 20 个列表/字典的情况下进行以下比较?

python - 如何在 IPython Notebook 中显示扩展模块的日志语句

python - 用于过滤空类别的上下文处理器

python - 当我从多个复选框获取数据时,格式是什么?我可以得到一份 list 吗?

javascript - 使用 Angular JS 显示第一个 JSON 数据对象而不选择任何链接

ios - 尝试将多个值附加到 Swift 字典中的同一个键