ValueError:太多的值无法在 Python 字典中解压

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17830778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:16:30  来源:igfitidea点击:

ValueError: too many values to unpack in Python Dictionary

pythondictionary

提问by Netorica

I have a function that accepts a string, list and a dictionary

我有一个接受字符串、列表和字典的函数

def superDynaParams(myname, *likes, **relatives): # *n is a list and **n is dictionary
    print '--------------------------'
    print 'my name is ' + myname

    print 'I like the following'

    for like in likes:
        print like

    print 'and my family are'

    for key, role in relatives:
        if parents[role] != None:
             print key + ' ' + role

but it returns an error

但它返回一个错误

ValueError: too many values to unpack

值错误:解包的值太多

my parameters are

我的参数是

superDynaParams('Mark Paul',
                'programming','arts','japanese','literature','music',
                father='papa',mother='mama',sister='neechan',brother='niichan')

采纳答案by Martijn Pieters

You are looping over a dictionary:

您正在遍历字典:

for key, role in relatives:

but that only yields keys, so one single object at a time. If you want to loop over keys and values, use the dict.items()method:

但这只会产生keys,所以一次一个对象。如果要遍历键和值,请使用以下dict.items()方法:

for key, role in relatives.items():

On Python 2, use the dict.iteritems()method for efficiency:

在 Python 2 上,使用dict.iteritems()方法提高效率:

for key, role in relatives.iteritems():

回答by Lucas Kauffman

You should use an iterator instead to iterate over the items:

您应该使用迭代器来迭代项目:

relatives.iteritems()

for relative in relatives.iteritems():
    //do something