Nanowatt
Nanowatt

Reputation: 33

How to add a another value to a key in python

First I'm sorry this might be a dumb question but I'm trying to self learn python and I can't find the answer to my question.

I want to make a phonebook and I need to add an email to an already existing name. That name has already a phone number attached. I have this first code:

phonebook = {}
phonebook ['ana'] = '12345'
phonebook ['maria']= '23456' , '[email protected]'

def add_contact():
       name = raw_input ("Please enter a name:")
       number = raw_input ("Please enter a number:")
       phonebook[name] = number

Then I wanted to add an email to the name "ana" for example: ana: 12345, [email protected]. I created this code but instead of addend a new value (the email), it just changes the old one, removing the number:

def add_email():
       name = raw_input("Please enter a name:")
       email = raw_input("Please enter an email:")
       phonebook[name] = email

I tried .append() too but it didn't work. Can you help me? And I'm sorry if the code is bad, I'm just trying to learn and I'm a bit noob yet :)

Upvotes: 0

Views: 114

Answers (1)

user2555451
user2555451

Reputation:

append isn't working because the dictionary's values are not lists. If you make them lists here by placing them in [...]:

phonebook = {}
phonebook ['ana'] = ['12345']
phonebook ['maria'] = ['23456' , '[email protected]']

append will now work:

def add_contact():
   name = raw_input("Please enter a name:")
   number = raw_input("Please enter a number:")
   phonebook[name].append(number)

Upvotes: 4

Related Questions