Python: Dictionaries

Go to Chapter 25 in A Smarter Way.

Python dictionaries are lists of key/value pairs:

name: Bill
address: 123 Main St.
telephone: 222-333-4444

Go to Chapter 26 in A Smarter Way.

Remember that key: value syntax. You’ll use it to create dictionaries:

best_friend = {"name": "bill", 
               "address": "1232 main st.", 
               "telephone": "222-333-4444"}

Note those curly braces: { }.

Go to Chapter 27 in A Smarter Way.

In a dictionary, you extract an element by naming its key:

best_friend_name = best_friend["name"]

Notice that we’re getting the value we want by using an index (that’s why we use square brackets), but the index isn’t a number, it’s a string (that’s why it’s in quotes).

Go to Chapter 28 in A Smarter Way.

Both keys and values can be numbers, if needed. Simply don’t place them in quotes:

cat_ranking = {1: "Ginger", 
               2: "Sven", 
               3: "Betty"}

Go to Chapter 29 in A Smarter Way.

To add items to a dictionary:

best_friend["ranking"] = 1

Go to Chapter 30 in A Smarter Way.

To remove items:

del best_friend["ranking"]

Again, note that we’re using square brackets, because we’re getting the value by using its key (index).

To change an item:

best_friend["address"] = "456 second st."

Go to Chapter 31 in A Smarter Way.

To loop through values:

for best_friend_info in best_friend.values():

Note how we use best_friend.values( ).

Go to Chapter 32 in A Smarter Way.

To loop through keys:

for each_key in best_friend.keys( ):

Again, note how we access the keys with best_friend.keys( ).

Go to Chapter 33 in A Smarter Way.

To loop through both keys and values:

for each_key, each_value in best_friend.items( ):
    print(each_key + ": " + each_value

This time we use items( ) instead of keys( ) or values( ).

Create and access multi-level dictionaries:

# Author: Armando S. Romero III
# used by permission
patients = {}
patients['PHP'] = {}
patients['MCD'] = {}


pat1 = {'name' : 'Amos' , 'ph' : '505-233-1234' }
pat2 = {'name' : 'Andy' , 'ph' : '505-233-4321' }
pat3 = {'name' : 'Armand' , 'ph' : '505-455-2222' }

patients['PHP'][10000] = pat2
patients['MCD'][10003] = pat3
patients['PHP'][10002] = pat1



and continue through chapter 33.

  1. Copy the multi-level dictionary above, and use it as a start to create a script that prints formatted output of this information, along the lines of a patients information report.