Home > Net >  Add multiple values to a key in python dictionary
Add multiple values to a key in python dictionary

Time:10-12

I 've noticed that a similar question has been asked before but none of those solutions could solve my problem. The question is:

Please write a phonebook application. The expected result should be:

command (1 search, 2 add, 3 quit): 2
name: peter
number: 040-5466745
ok!
command (1 search, 2 add, 3 quit): 2
name: emily
number: 045-1212344
ok!
command (1 search, 2 add, 3 quit): 1
name: peter
040-5466745
command (1 search, 2 add, 3 quit): 1
name: mary
no number
command (1 search, 2 add, 3 quit): 2
name: peter
number: 09-22223333
ok!
command (1 search, 2 add, 3 quit): 1
name: peter
040-5466745
09-22223333
command (1 search, 2 add, 3 quit): 3
quitting...

Hereinbelow is my code:

database={}
def add():
    name=input("name: ")
    number=int(input("number:"))
    print("ok")
    if name not in database.keys():
      
        database[name]=number
       
    else:
        database[name].append(number)
        
       
    return database
def search():
    name=input("name: ")
    if name in database.keys():
        print(database[name])
    else:
        print("no number")
        
def main(comment):
    while True:
        comment=int(input("Please give a comment:"))
        if comment==2:
            add()
        if comment==1:
            search()
        if comment==3:
            print("bye")
            break

main(2)

The error message I 've got is "AttributeError: 'int' object has no attribute 'append'". How can I solve it? Thanks!

Please give a comment:
2
name: 
peter
number:
010202
ok
Please give a comment:
2
name: 
peter
number:
34440
ok
Traceback (most recent call last):
  File "main.py", line 33, in <module>
    main(2)
  File "main.py", line 26, in main
    add()
  File "main.py", line 11, in add
    database[name].append(number)
AttributeError: 'int' object has no attribute 'append'


** Process exited - Return Code: 1 **
Press Enter to exit terminal
Online Py

How can I solve it? Thanks!

CodePudding user response:

You should familiarise yourself with appropriate techniques for populating a dictionary. Think about whether (or not) it's necessary to convert input values. This can be simply implemented as:

database = {}

def add():
    name = input('Name: ')
    number = input('Number: ')
    database.setdefault(name, []).append(number)

def search():
    name = input('Name: ')
    print(', '.join(database.get(name, ['Not found'])))

while True:
    match input('Command - 1 search, 2 add, 3 quit: '):
        case '1':
            search()
        case '2':
            add()
        case '3':
            break
        case _:
            print('Invalid command')

CodePudding user response:

Just few changes database[name]=number to database[name]=[number]

database={}
def add():
    name=input("name: ")
    number=input("number:")
    print("ok")
    if name not in database.keys():
      
        database[name]=[number]  # changes
       
    else:
        database[name].append(number)
        
       
    return database
def search():
    name=input("name: ")
    if name in database.keys():
        print(database[name])
    else:
        print("no number")
        
def main(comment):
    while True:
        comment=int(input("Please give a comment:"))
        if comment==2:
            add()
        if comment==1:
            search()
        if comment==3:
            print("bye")
            break

main(2)

as suggested by @oldBill int(input("number:")) to input("number:")

CodePudding user response:

You'd have to change the content of database[name] to a list that includes 1 or more phone numbers, because int objects are not lists.

CodePudding user response:

You have to first convert the value for the relative key to list, then you can append items:

database={}
def add():
    name=input("name: ")
    number=int(input("number:"))
    print("ok")
    if name not in database.keys():
        database[name]=number
    elif type(database[name]) != list:
        database[name] = [database[name]]
        database[name].append(number)
    else: 
        database[name].append(number)
return database

def search():
    name=input("name: ")
    if name in database.keys():
        print(database[name])
    else:
        print("no number")
    
def main(comment):
    while True:
        comment=int(input("Please give a comment:"))
        if comment==2:
            add()
        if comment==1:
            search()
        if comment==3:
            print("bye")
            break

Also, the argument comment for the function main() is useless since you're calling an input to declare the variable

  • Related