ValueError: too many values to unpack (expected 2)

时间:2022-07-22
本文章向大家介绍ValueError: too many values to unpack (expected 2),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
交流、咨询,有疑问欢迎添加QQ 2125364717,一起交流、一起发现问题、一起进步啊,哈哈哈哈哈
    

    
class Mymeta(type):

    def __new__(cls, class_name, class_bases, class_attrs):
        print('--->', cls)  # ---> <class '__main__.Mymeta'>
        print('--->', class_name)  # ---> Chinese
        print('--->', class_bases)  # ---> (<class 'object'>,)
        print('--->', class_attrs)  # 'Chinese', 'country': 'china', 'skin': 'yello', '__init__': ....
        print(class_attrs.items())
        update_attrs = {}
        for key, value in class_attrs:
            if not callable(value) and not key.startswith('__'):
                update_attrs[key.upper()] = value
            else:
                update_attrs[key] = value

        return type.__new__(cls, class_name, class_bases, update_attrs)


class Chinese(object, metaclass=Mymeta):
    country = 'china'
    skin = 'yello'

返回了下面的错误:

    for key, value in class_attrs:
ValueError: too many values to unpack (expected 2)

原因是字典这个是一个迭代器对象,参考官方文档找到下列说明,字典只支持Key的遍历,,如果想对key,value,则可以使用items方法。 The “implicit” iteration that dictionaries support only iterates over keys.

python只支持对于key的遍历,所以不能使用for k,v这种形式,这个时候会提示ValueError: too many values to unpack,

各位看官老爷,如果觉得对您有用麻烦赏个子,创作不易,0.1元就行了。下面是微信乞讨码:

添加描述

添加描述 正确代码如下:

for key, value in class_attrs.items():