Python Concepts/Dictionaries

Objective

 * Learn about Python dictionaries.
 * Learn about the dictionary's syntax.
 * Learn about built-in dictionary functions.
 * Work with loops using dictionary keys and values.
 * Learn when to use dictionaries and when not to.

Page Index

 * Dictionaries:Lesson
 * Dictionaries:Basic operations on dictionaries
 * Dictionaries:Dictionary views
 * Dictionaries:Other operations on dictionaries
 * Dictionaries:An elementary database
 * Dictionaries:Assignments
 * Dictionaries:References

Lesson
Python dictionaries are (apparently) random sequences that contain a set of keys, where each key points to a value and is associated with that value, hence the expression "associative arrays" sometimes found in other languages. Dictionaries act just like real life dictionaries, where the key is the word and the value is the word's definition.

An English dictionary, for example, may contain hundreds of thousands of words. Because each word is put into the dictionary in a well defined way, the word and its definition can be found very quickly. In any real life dictionary words can be added or deleted at any time and the definition of an existing word can be changed. Although an English dictionary may appear to contain several definitions of the same word, "house (noun)" and "house (verb)" are separate entries. Python's dictionaries are conceptually similar, but the ordering of the keys may seem random. However, entries are put into Python's dictionaries in a well defined way, so that each key and its associated value may be retrieved very quickly.

Dictionaries use the curly braces like the set, however empty curly braces create a dictionary.

In technical terms the dictionary is an object that maps hashable values (keys) to arbitrary objects (values). A hashable value is a value that can be included as a member of a set. If you think of keys as numbers or strings, you can do much with dictionaries.

Dictionary views
The objects returned by  are view objects. They provide a dynamic view of the dictionary’s entries, which means that when the dictionary changes, each view reflects these changes.

Values not unique: Retrieve the keys: Retrieve the values Retrieve keys and values as a sequence of (key,value) pairs where each pair is a tuple Views are dynamic: Iterations over keys, values, items: Summary:

Other operations on dictionaries
Introduction to :

Return a new dictionary initialized from an optional positional argument and a possibly empty set of keyword arguments.

Arguments may be supplied to the  constructor as follows:

where:

means a possibly empty set of keyword arguments such as: one=1, two=2, three=3

"mapping" means dictionary, and

"iterable" means an iterable object (such as list or tuple) each item of which must be an iterable with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value. If a key occurs more than once, the last value for that key silently becomes the corresponding value in the new dictionary.

To illustrate, consider the following python code:

The above code produces:

For a deep copy:

Same as  without raising

If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a  is raised.

Good programming requires that we anticipate and process errors. (Unless you really want to produce ) No phone number for Jimbo

George's phone number was 2235

phoneNumbers = {}

What if 'Jimbo' was in  with a value of  ?

The above code produces the same results.

Remove and return an arbitrary (key, value) pair from the dictionary. popitem is useful to iterate destructively over a dictionary. If the dictionary is empty, calling popitem raises a

If key is in dictionary, return value. If not, insert key with a value of default and return default (which defaults to )

Update the dictionary with the key:value pairs from other, overwriting existing keys. Return. accepts arguments like the arguments to  above.

The above code takes

An elementary database
Let's use the python dictionary to build an elementary database, "friends:"

The information which we'd like to include is: name, age, address, phone number, hobbies. Add entries to "friends:"

Access the data in the database:

Bill's age is 22

Alan's address is Brown Street

Tim's phone number is 3456

Linda's hobbies are ['old movies']

Jenny's hobbies are ['old movies', 'cycling', 'video games', 'genealogy']

Make the code more readable:

Output is same as above. Make the output of 'hobbies' more readable:

Nothing for Bill under 'hobbies'.

Alan's hobbies are: cycling, stamp collecting.

Tim's hobbies are: parachuting, video games, athletics.

Linda's hobby is: old movies.

Jenny's hobbies are: old movies, cycling, video games, genealogy.

Add more information to the database:

Check the additional data:

Bill 'Ford', 'classic', 1948, ['v8', 'ohv', 'water-cooled', 'Ford']

Alan []

Tim ['Toyoya', 'Chevy']

Linda ['Volvo']

Jenny ['Subaru']

This is a simple database and already it's becoming complicated:

classic

water-cooled

What if you decide to expand the information in ? For example:

Fortunately, python's list processing capabilities are powerful and almost unlimited.

Some advanced operations on the database

Show the names of all your friends who live on Brown street.

Alan lives on Brown Street.

Linda lives on Brown Street.

Show the names of all your friends who enjoy video games.

Tim enjoys video games.

Jenny enjoys video games.

Show the names of all your friends who own a classic car with an 'ohv' engine.

Bill has one.

Integrity of the database -

From time to time review the data in the database and verify that it makes sense and has not been corrupted.

If you see a friend's age as 112, would this make sense?

In a multi-item cell like "hobbies" remove duplicates:  should be

Does a list like  make sense?

Would you keep a hobby like 'robbing banks' in your database?

Assignments



 * Previous Lesson: Sets
 * This Lesson: Dictionaries
 * Next Lesson: If Statement
 * Course Home Page