Dictionaries in Python

Dictionaries in Python are basically the same as real-life dictionaries. They both hold
information in similar ways. A real-life dictionary is just a book of words and
definitions. It’s the same with Python dictionaries. They hold keys(words) and
values(definitions). A key can be any immutable object: number, string, or tuple.
Check out how to make a dictionary.

dictionary = {'name' : 'Rose', 'age': 110, 99: 'bottles'}

So first we have the name of our dictionary (aptly named dictionary). Then we have
our keys: name, age, 99, each followed by ‘ : ‘ and then their values: Rose, 110,
bottles. All this encapsulated in brackets {} .
If we want to add a key/value pair to our existing dictionary, we would do so like this:

dictionary['size'] = 'obese'

Exact same thing for changing a dictionary value:

dictionary['size'] = 'petite'

Now we can either type dictionary or print dictionary and it will show us all the keys
and values in the dictionary:
{‘name’ : ‘Rose’, ‘age’:110, 99:’bottles’, ‘size’:’obese’}

To access a value for a specific key:

dictionary['name']

We delete a dictionary entry like this:

del dictionary['99']

Which would delete the pair 99:’bottles’.
Let’s see a dictionary in action:

def show_menu(): 
    print "\n1. Show phone numbers" 
    print "2. Add Phone number" 
    print "3. Delete Phone number" 
    print "0. Exit\n" 
    return input("Please enter selection: ") #returns our input to
selection 
def show_phonelist(phonelist): 
    for keys in phonelist.keys(): #keys() retrieves all the keys of the
dictionary
        print keys, phonelist[keys] #Prints the keys and
values                   
def add_phone(phonelist): 
    name = raw_input("Please enter name: ") 
    phone = raw_input("Please enter phone number: ") 
    phonelist[name] = phone #Add key/value pair to dictionary 
    return phonelist #return updated dictionary 
def del_phone(phonelist): 
    name = raw_input("Enter name to delete: ") 
    if name in phonelist.keys(): #Check to make sure key is in dictionary
        del phonelist[name] #delete record 
        print "deleted!" 
        return phonelist #return updated dictionary 
    else: 
        print "That name is not on record." 
phonelist = {"Kathy":"503-666-1234", "Bob":"451-883-2412"}   #Create
dictionary   
running = 1 
while running: 

    selection = show_menu() #get selection from show_menu() function 
    if selection == 1: 
        show_phonelist(phonelist) #show dictionary 
    elif selection == 2: 
        phonelist = add_phone(phonelist) #use add_phone() function and
update     
    elif selection == 3: 
        phonelist = del_phone(phonelist) #use del_phone() function and
update     
    elif selection == 0: 
        running = 0 
    else: 
        print "That is not a valid option."

Most of this program should make sense to you if you have been following the
tutorial. To start the program I made it a little more legible by defining functions. The
first function – show_menu() – simply shows us our menu, gets the users selection and
returns it to our main program. show_phonelist() takes the dictionary and shows us all
the keys and values of the dictionary. add_phone() takes our dictionary, adds to it, and
return it back to the main program with the added entry. While del_phone() deletes an
entry, and returns the dictionary to the main program. The next part of the program is
just initiating our dictionary. We also could have started with an empty dictionary:

phonelist = {}

Now for the main part of our program, running is set to 1 until such time as the user
chooses 0 as a selection, hence the while statement. All the rest should look pretty
familiar. If the user selects 1, we call the show_phonelist() function.
If the user selects 2 we call the add_phonelist() function by assigning the results to
phonelist. Same thing for selection 3.
Dictionaries are a very useful tool in programming. They can hold any information
that a list or tuple can, including lists, tuples, other dictionaries and even class
instances!
Now what if we wanted to hold more information about a person, other than their
phone number? The ideal way is going to be with a class. But you could also nest
dictionaries and/or lists. For example:

attributes = {"age":21, "phone":"555-555-5555"}
dictionary = {"brad":attributes}

should give you something that looks like this:

{‘brad’: {‘phone’: ‘555-555-5555’, ‘age’ : 21}}
Another cool thing about dictionaries is that you can turn any two lists of the same
size into a dictionary by using zip() and dict(). The zip() function will combine any
two lists (technically any number of lists, but for a dictionary only two will work).
Like so:
names = “Joe”, “Fred”, “Rita”
size = “Fat”, “Thin”, “Anorexic”
combine = zip(names, size) 
With combine looking like this:
[(‘Joe’, ‘Fat’), (‘Fred’, ‘Thin’), (‘Rita’, ‘Anorexic’)]
Now to turn this into a dictionary we simply use the dict() function:

newdict = dict(combine)

The dict() function will work with any list(or more precisely lists within a list) with
the format above.
So there are the basics of dictionaries. Again, if there are any questions, comments, or
concerns. Please feel free to email me at [email protected] Check out the
practice below and then we’ll see if we can’t save these records in a permanent file!

Practice

  1. Add an option that lets the user change current information in database
  2. See if you can have the user add more information such as hair color, or annual pay
    to the database in our phonebook