Dictionaries

CS 65: Introduction to Computer Science I

Analogies: physical dictionaries

How do we use physical dictionaries?

  • Look up a word
  • Retrieve a definition

Python dictionaries work like this too

In [1]:
cs_dept_phonebook = { 
                        "Porter"  : "3041",
                        "Case"    : "4618",
                        "Klinge"  : "4599",
                        "Manley"  : "2177",
                        "Urness"  : "2188",
                        "Rieck"   : "3795"
                    }
In [2]:
cs_dept_phonebook["Manley"]
Out[2]:
'2177'

Each item in a dictionary is a key-value pair

Use a key to look up a value

"Manley" is a key

"2177" is a value

Things to notice about the syntax

Uses curly braces { }, keys and values are separated with colons :, and each key-value pair is separated by commas ,

The spacing in this example is just to make it look nice - you don't have to do any indenting or newlines.

In [3]:
cs_dept_phonebook = { 
                        "Porter"  : "3041",
                        "Case"    : "4618",
                        "Klinge"  : "4599",
                        "Manley"  : "2177",
                        "Urness"  : "2188",
                        "Rieck"   : "3795"
                    }

Accessing a value is the same as with a list, but you can put anything inside the [ ] brackets.

In [4]:
cs_dept_phonebook["Manley"]
Out[4]:
'2177'

Basic Dictionary Operations

Dictionaries are mutable, so you can change them.

Updating a value

In [6]:
cs_dept_phonebook["Urness"] = "2118"
cs_dept_phonebook
Out[6]:
{'Porter': '3041',
 'Case': '4618',
 'Klinge': '4599',
 'Manley': '2177',
 'Urness': '2118',
 'Rieck': '3795'}

You can assign a value to a new key that isn't in the dictionary yet, and it will add it.

In [7]:
cs_dept_phonebook["Moore"] = "5555"
print(cs_dept_phonebook)
{'Porter': '3041', 'Case': '4618', 'Klinge': '4599', 'Manley': '2177', 'Urness': '2118', 'Rieck': '3795', 'Moore': '5555'}

They're not considered ordered - you can't guarantee what order they'll be displayed in.

Delete dictionary elements with pop() method

In [8]:
cs_dept_phonebook.pop("Rieck")
print(cs_dept_phonebook)
{'Porter': '3041', 'Case': '4618', 'Klinge': '4599', 'Manley': '2177', 'Urness': '2118', 'Moore': '5555'}

Group Exercises:

Exercise 1: Write a program that asks the user for a name and phone number and then adds that to the phonebook.

In [ ]:
name = input("Enter a name: ")
number = input("Enter a phone number: ")
#fill in the blank here

Exercise 2: Write a program to ask the user for a name and then display the phone number in the phone book for that name. What happens is they enter a name that isn't in the phone book? Come up with an idea for how that can be handled (Hint: experiment using an if statement and the in operator)

In [13]:
name = input("Enter a name: ")
#fill in the blank here
Enter a name: Eric

Types in dictionaries

Keys can be anything of any type (though they are usually strings)

Values can be anything - even other containers like lists or other dictionaries

In [9]:
math_dict = { 3.14 : "This is an approximation of pi.", 
            1 : "This is the number 1", 
            2.718 : "This is an approximation of the natural log base.",
            (0,0) : "This is the origin in two-dimensional space",
            "zero" : 0,
            "Fibonacci sequence" : [1,1,2,3,5,8,13,21,34] }

print(math_dict[3.14])
print(math_dict[1])
print(math_dict[(0,0)])
print(math_dict["zero"])
print(math_dict["Fibonacci sequence"])
This is an approximation of pi.
This is the number 1
This is the origin in two-dimensional space
0
[1, 1, 2, 3, 5, 8, 13, 21, 34]

Looping through a dictionary

You can loop through a dictionary with a for loop, though it will only run through each of the keys. You can then use the key to get the value.

In [10]:
for key in cs_dept_phonebook:
    print(key,"'s office phone extension is",cs_dept_phonebook[key])
Porter 's office phone extension is 3041
Case 's office phone extension is 4618
Klinge 's office phone extension is 4599
Manley 's office phone extension is 2177
Urness 's office phone extension is 2118
Moore 's office phone extension is 5555