【问题标题】:too many values to unpack on dictionary key value iteration [closed]在字典键值迭代中解包的值太多[关闭]
【发布时间】:2020-05-02 17:16:36
【问题描述】:

收到错误太多值无法解压。谁能帮我解决一下?

friendship = {'nino': ["tamari", "nika", "lela", "dato"],
              'dato': ["tamari", "nino"],
              'tamari': ["nino", "dato", "lela"],
              'nika': ["nino"],
              'lela': ["nino", "tamari"]
}
def f(**friendship):
    sia={}
    for i in friendship.values():
        m = min(i)
        for k,v in friendship.items():
            sia.update({k:(len(v))})
        low = min(sia.values())
        res = [x for x,y in sia if sia.items() if y == low]

    print(str(res) + " has " + str(low) + " friends")   ------ getting an error on this line.
print (f(**friendship))

【问题讨论】:

  • 打印 (f(friendship))
  • 错误实际上是在res = [x for x,y in sia if sia.items() if y == low]。如果您尝试@High-Octane 的建议,错误将变为TypeError: f() takes 0 positional arguments but 1 was given
  • 该方法的目标是什么?你期待什么结果?

标签: python dictionary key-value valueerror


【解决方案1】:

问题是在x,y in sia 处解包以使键/值使用items() 并删除无用的if,像这样

[x for x, y in sia.items() if y == low]

您也可以在这两个地方删除** 运算符,因为直接传递字典是没用的,它会导致数据扁平化,然后在方法中再次打包

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    • 2017-11-22
    • 2016-01-04
    • 2023-04-06
    • 2017-12-05
    • 2021-04-05
    相关资源
    最近更新 更多