Search code examples
pythonpython-3.xtuplesiterable-unpacking

Not enough values to unpack from dictionary items: expected 3 values, got 2


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()

Solution

  • 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.