Whenever I run this code, python gives me:
ValueError: not enough values to unpack (expected 3, got 2)
I'm trying to make a kind of an address book where you can add, delete and change information. I was trying to change the code in line 20 where there is a for
-in
loop (this line is actually a source of problem) but it didn't give any result.
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 protected]', '43454')
Member.Check()
Verify the assignment variables. If the number of assignment variables is greater than the total number of variables, delete the excess variable from the assignment operator. The number of objects returned, as well as the number of variables available are the same. This will resolve the value error.
Solution. While unpacking a list into variables, the number of variables you want to unpack must equal the number of items in the list. If you already know the number of elements in the list, then ensure you have an equal number of variables on the left-hand side to hold these elements to solve.
The “ValueError: not enough values to unpack” error is raised when you try to unpack more values from an iterable object than those that exist. To fix this error, make sure the number of values you unpack from an iterable is equal to the number of values in that iterable.
The valueerror: too many values to unpack occurs during a multiple-assignment where you either don't have enough objects to assign to the variables or you have more objects to assign than variables.
The error pretty much tells you what's going on: you're trying to unpack 3 items from a list but members.items()
is returning a dict_items
class of key-value pairs, each of which looks like
('Tim', ['[email protected]', '43454'])
You can use
name, info in members.items()
where info
is a tuple of (email, number)
or
name, (email, number) in members.items()
to unpack the value tuple into two distinct variables directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With