Home > Net >  How to add new key-value to dictionary
How to add new key-value to dictionary

Time:09-30

contacts = {'John Smith': '1-123-123-123',
            'Jane Smith': '1-102-555-5678',
            'John Doe': '1-103-555-9012'}


def add_contact(contacts, name, number):
    """
    Add a new contact (name, number) to the contacts list.
    """
    if name in contacts:
        print(name, "is already in contacts list!")
    else:
        contacts[name] = number

print(add_contact(contacts, 'new_guy', '1234'))

When I print this I get none

but if I add another line print(contacts)

it will give me a none and the new dictionary with 'new_guy' :'1234'. What is the correct way to print out the new dictionary without printing none?

CodePudding user response:

You're adding to the dictionary correctly. Yor print statement is the issue.

Change this:

print(add_contact(contacts, 'new_guy', '1234'))

You need to separate this out some.

add_contact(contacts, 'new_guy', '1234')
print(contacts)

Also, since your contacts dictionary is declared globally, you don't need to pass it to the function. You could change the function to:

def add_contact(name, number):

CodePudding user response:

The way you have it right now, you are printing what the function returns (which is none). All you need to do is separate your functional call and print statement like so:

    add_contact(contacts, 'new_guy', '1234')
    print(contacts)

CodePudding user response:

def add_contact(name, number):
    """
    Add a new contact (name, number) to the contacts list.
    """
    if name in contacts:
        print(name, "is already in contacts list!")
    else:
        contacts[name] = number
    return contacts #put a return statement that will return the updated contacts dictionary

print(add_contact('John Doe', '1234'))


#for simplified version try a dictionary comprehension:
#using the dict.update(), we can use a comprehension inside to iterate from the contacts itself and have a condition if the name is already exists
contacts.update({key: value for key, value in contacts.items() if key not in contacts})

#tho, we can't have a print statement that will tell if the name already exist in the contacts
print(contacts)

>>>output: {'John Smith': '1-123-123-123', 'Jane Smith': '1-102-555-5678', 'John Doe': '1-103-555-9012'}
  • Related