没有足够的值从字典项中解包:预期 3 个值,得到 2 个
Not enough values to unpack from dictionary items: expected 3 values, got 2
每当我 运行 这段代码时,python 都会给我:
ValueError: not enough values to unpack (expected 3, got 2)
我正在尝试制作一种地址簿,您可以在其中添加、删除和更改信息。我试图更改第 20 行的代码,其中有一个 for
-in
循环(这一行实际上是问题的根源)但它没有给出任何结果。
members = {}
class Member:
def __init__(self, name, email, number):
self.name = name
self.email = email
self.number = number
def addmember(name, email, number):
members[name] = email, number
print('Member {0} has been added to addressbook'.format(name))
def Check():
print("You've got {0} members in your addressbook".format(len(members)))
for name, email, number in members.items(): #the problem is here
print('Contact {0} has email:{1} and has number:{2}'.format(name, email, number))
print('')
Member.addmember('Tim', 'email@mail.com', '43454')
Member.Check()
该错误几乎可以告诉您发生了什么:您正在尝试从列表中解压 3 项,但 members.items()
返回 dict_items
class of key-value对,每对看起来像
('Tim', ['email@mail.com', '43454'])
您可以使用
name, info in members.items()
其中 info
是 (email, number)
或
的元组
name, (email, number) in members.items()
将值元组直接解包为两个不同的变量。
每当我 运行 这段代码时,python 都会给我:
ValueError: not enough values to unpack (expected 3, got 2)
我正在尝试制作一种地址簿,您可以在其中添加、删除和更改信息。我试图更改第 20 行的代码,其中有一个 for
-in
循环(这一行实际上是问题的根源)但它没有给出任何结果。
members = {}
class Member:
def __init__(self, name, email, number):
self.name = name
self.email = email
self.number = number
def addmember(name, email, number):
members[name] = email, number
print('Member {0} has been added to addressbook'.format(name))
def Check():
print("You've got {0} members in your addressbook".format(len(members)))
for name, email, number in members.items(): #the problem is here
print('Contact {0} has email:{1} and has number:{2}'.format(name, email, number))
print('')
Member.addmember('Tim', 'email@mail.com', '43454')
Member.Check()
该错误几乎可以告诉您发生了什么:您正在尝试从列表中解压 3 项,但 members.items()
返回 dict_items
class of key-value对,每对看起来像
('Tim', ['email@mail.com', '43454'])
您可以使用
name, info in members.items()
其中 info
是 (email, number)
或
name, (email, number) in members.items()
将值元组直接解包为两个不同的变量。