16 Dictionaries in Python
16 Dictionaries in Python
Jerry Cain
CS 106AX
October 31, 2022
slides leveraged from those constructed by Eric Roberts
Dictionaries in Python
• Like most modern programming languages, Python provides a
data structure allowing us to associate pairs of data values.
Although the more common term in computer science is map,
Python calls this structure a dictionary.
• A dictionary associates a simple data value called a key (most
often a string) with a value, which is often larger and more
complex.
• Applications of the map idea exist everywhere in the real
world. A classic example—which is where Python gets the
name—is a dictionary. The keys are the words, and the values
are the corresponding definitions.
• You’ll be relying on strings, lists, and dictionaries for
Assignment 5, which goes out on Wednesday.
Dictionaries in Python
• Dictionaries in Python are similar in syntax to lists. In both
data models, the fundamental operation is selection, which is
indicated using square brackets. The difference is that index
values for a dictionary need not be integers.
• When you look up a value in a dictionary, you supply the key
as a string expression using the square-bracket notation, as in
map[key]
• You can also use the items method to iterate through the keys
and values together:
for key, value in dict.items():
. . . code to work with the individual key and value . . .
Finding Airports by Location
Symbol Tables
• Programming languages make use of dictionaries in several
contexts, of which one of the easiest to recognize is a symbol
table, which keeps track of the correspondence between
variable names and their values.
• The SymbolTable.py application in the text implements a
simple test of a symbol table that reads lines from the console,
each of which is one of the following commands:
– A simple assignment statement of the form var = number.
– A variable alone on a line, which displays the variable’s value.
• Before running the program, we’re going to add two new
features:
– The command list, which lists all the variables.
– The command quit, which exits from the program.
Sample Run of SymbolTable.py
SymbolTable
> pi = 3.14159
> e = 2.71828
> x = 2
> pi
3.14159
> x
2
> list
e = 2.71828
pi = 3.14159
x = 2
> x = 42
> a = 1.5
> list
a = 1.5
e = 2.71828
pi = 3.14159
x = 42
> quit
The End