CIT228 - Advanced Database Systems

 Python Dictionaries


I. Overview

Chapter 6 covers Python dictionaries which are another data type you can utilize. 

To see an explanation of all lecture material in chapter 6, watch: https://youtu.be/KPbBw8PftPQ

To see sample exercises that go with the Try It Yourself sections in the chapter, download: chapter_06.zip


II. Creating Python Dictionaries

Python dictionaries are used to store data in key:value pairs.   (They are similar to associative arrays which are used in other languages like PHP.) 

Accessing data in dictionaries requires subscripting into the dictionary using the key.

Key values within a dictionary must be unique.

Since dictionaries are set up with keys, they are "unordered".

Values that are stored can be duplicated, but they keys cannot be duplicated.

Values that are stored can be changed by subscripting into the dictionary and assigning a different value to the key.

There is no limit to the number of key:value pairs within a single dictionary.

A.  Creating a Dictionary

There are two different ways you can code a dictionary:  vertical and horizontal.   The method you choose depends upon personal preference.

Horizontal Method Syntax:

dictionaryName = { "key1":value1, "key2":value2, "keyn":valuen}

This method works well if you don't have a large number of key:value pairs.

Example showing data added to a dictionary:

employee = {"Number":100,"Name":"Fred Flintstone","Title":"Boss","Salary":50000}

print(employee)

Sample Output

{'Number': 100, 'Name': 'Fred Flintstone', 'Title': 'Boss', 'Salary': 50000}

Vertical Method Syntax:

dictionaryName = {
     "key1":value1,
      "key2":value2,
      "keyn":valuen,
}

If you have a large number of key:value pairs, this method works better. 

When using the vertical method, it’s good practice to include a comma after the last key-value pair, so you are ready to add a new key-value pair on the next line.

Example showing data added to a dictionary:

employee = {
    "Number":100,
    "Name":"Fred Flintstone",
    "Title":"Boss",
    "Salary":50000,
}

print(employee)

Sample Output:

{'Number': 100, 'Name': 'Fred Flintstone', 'Title': 'Boss', 'Salary': 50000}

Example showing an empty dictionary with data added later:

employee={}

B.  Accessing a key:value pair

To access a key:value pair, you must subscript into the dictionary using the key

Syntax:   dictionaryName["key"]

Examples:

print("The employee's name is: ", employee["Name"])

print(employee["Name"], " is the ", employee["Title"].lower())

Sample Output

The employee's name is: Fred Flintstone

Fred Flintstone is the boss

C. Adding to an existing dictionary

Adding to a dictionary is similar to adding properties to classes in other languages, all you need to do is subscript into the dictionary with a new key and assign a value to it.

Syntax:  dictionaryName["newKey"] = "new value"

Example:

employee = {"Number":100,"Name":"Fred Flintstone","Title":"Boss","Salary":50000}

employee["performanceReview"]="10/10/2021"
employee["lastRaise"]="10/10/2020"

print(employee)

Sample Output:

{'Number': 100, 'Name': 'Fred Flintstone', 'Title': 'Boss', 'Salary': 50000, 'performanceReview': '10/10/2021', 'lastRaise': '10/10/2020'}

Example - adding to an empty dictionary:

ingredients = {}

ingredients["butter"]="3 tablespoons"
ingredients["marshmellows"]="1 10 oz package"
ingredients["rice krispies"]="5 cups for gooey treats, 6 for firmer treats"

print(ingredients)

Sample Output:

{'butter': '3 tablespoons', 'marshmellows': '1 10 oz package', 'rice krispies': '5 cups for gooey treats, 6 for firmer treats'}

D.  Modifying Values in a Dictionary

To modify a value, subscript into the dictionary using the key and assign a different value.

Syntax:  dictionaryName["key"] = "new value"

Example:

ingredients={"butter":"3 tablespoons", "marshmellows":"1 10 oz package","rice krispies":"5 cups for gooey treats, 6 for firmer treats"}
print(ingredients)
ingredients['rice krispies']="5.5 cups"
print(ingredients)

Sample Output:

{'butter': '3 tablespoons', 'marshmellows': '1 10 oz package', 'rice krispies': '5 cups for gooey treats, 6 for firmer treats'}
{'butter': '3 tablespoons', 'marshmellows': '1 10 oz package', 'rice krispies': '5.5 cups'}    

Example from the book that tracks an alien across the screen:

 
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print(f"Original position: {alien_0['x_position']}")

# Move the alien to the right.
# Determine how far to move the alien based on its current speed.
if alien_0['speed'] == 'slow':
    x_increment = 1
elif alien_0['speed'] == 'medium':
    x_increment = 2
else:
    # This must be a fast alien.
    x_increment = 3

# The new position is the old position plus the increment.       
alien_0['x_position'] = alien_0['x_position'] + x_increment

print(f"New position: {alien_0['x_position']}")
	

Sample Output:

Original position: 0
New position: 2

E.  Removing Key:Value Pairs

The del command can be used to remove key:value pairs from a dictionary

Syntax:  del dictionaryName["key"]

Example:

employee={"Number":100,"Name":"Fred Flintstone","Title":"Boss","Salary":50000}

employee["performanceReview"]="10/10/2021"
employee["lastRaise"]="10/10/2020"

print(employee)

del employee["performanceReview"]

print(employee)

Sample Output:

{'Number': 100, 'Name': 'Fred Flintstone', 'Title': 'Boss', 'Salary': 50000, 'performanceReview': '10/10/2021', 'lastRaise': '10/10/2020'}
{'Number': 100, 'Name': 'Fred Flintstone', 'Title': 'Boss', 'Salary': 50000, 'lastRaise': '10/10/2020'}

F.  get() method

Subscripting into dictionaries is great if the key exists; however, if the key doesn't exist it will produce an error. 

The get() method lets you access the dictionary with the key; BUT if it doesn't exist, you can temporarily assign a value to the key instead of getting the error.

NOTE:  The key and the value assigned are not added to the dictionary, they are just used in the statement that contains the get method

Syntax:   dictionaryName.get("key", "new value if it isn't there")

If you omit the new value, Python will just use "none" if the key doesn't exist.  None is not an error condition, it is similar to null, it just means there is no value

Example:

puppy={"color":"white", "eyes":"black"}
print(puppy)
dogBreed=puppy.get("breed","Malteese")
dogColor=puppy.get("color","unknown")
print(dogBreed)
print(dogColor)
print(puppy)

Sample Output:

{'color': 'white', 'eyes': 'black'}
Malteese
white
{'color': 'white', 'eyes': 'black'}

A few things to note:

1. The get() method didn't add the breed to the dictionary, it simply allowed a value, Malteese, to be assigned to a dogBreed variable
2. The get() method was able to retrieve the correct color from the dictionary and store it in the dogColor variable because the key existed
3. Anytime there is a chance the key may not exist in a dictionary, you should use get() to avoid an error when the program runs


Hands On #1 -Practice creating and accessing dictionaries

To see a video demonstration, watch: https://youtu.be/qWm2qffWn1s

1. Open the CIT228 folder and create a new folder named Chapter6 

2.  Create a new file called fav_numbers.py and complete Try It Yourself 6-2 on page 99 (code the dictionary using either horizontal or vertical syntax)

Sample Output

Lisa, you're favorite number is: 20
Dan, you're favorite number is: 22
Danielle, you're favorite number is: 7
Dylan, you're favorite number is: 11
Leighton, you're favorite number is: 13

3.  Save all your changes.

4.  Create a new file called glossary.py and complete Try It Yourself 6-3 on page 99  (code the dictionary using vertical syntax since this is a dictionary that could be added to in the future)

To print the word on one line and the definition indented on the second line, you need to code it like the example shown below:

print("Dictionary:")
print("\t",glossary["dictionary"])

Sample Output:

 
Dictionary:
         Python data type that stores key:value pairs

5.  Save all your changes.


III. Looping through Dictionaries

If you want to access all values (or keys) in a dictionary, you can loop through the dictionary using a for loop.

The syntax varies depending upon what you want to return.

A.  Return the keys in the dictionary

Syntax:   

for item in dictionaryName:
    statement1
    statement2
    statementn

Where item represents the key.  If you use it alone, it is the key value

Example

puppy = {
      "breed": "Malteese",
      "color": "white",
      "eyes": "black"
}
for item in puppy:
      print(item)

Sample Output

breed  
color  
eyes

B.  Print all values individually

Syntax:

for item in dictionaryName:
    statement1
    statement2
    statementn

Where item is the key.  To access the dictionary value, you need to subscript into the dictionary using the key:  dictionaryName[item] 

Example:

puppy = {
     "breed": "Malteese",
     "color": "white",
     "eyes": "black"
}
for item in puppy:
     print(puppy[item])

Sample Output:

Malteese  
white  
black

C.  values() method

You can use the values method to retrieve values only in a for loop

Syntax:

for item in dictionaryName.values():
    statement1
    statement2
    statementn

Where item will represent the value being stored because of the values() method

Example:

puppy = {
      "breed": "Malteese",
      "color": "white",
      "eyes": "black"
}
for item in puppy.values():
      print(item)

Sample Output

Malteese
white
black

D.  keys() method

You can use the keys method to retrieve keys only in a for loop

Syntax:

for item in dictionaryName.keys():
    statement1
    statement2
    statementn

Where item will represent the key being stored because of the keys() method

Example:

puppy = {
      "breed": "Malteese",
      "color": "white",
      "eyes": "black"
}
for item in puppy.keys():
      print(item)

Sample Output:

breed  
color  
eyes

 

E.  items() method

The items() method lets you retrieve BOTH keys and values.

Syntax:

for key, value in dictionaryName.items():
    statement1
    statement2
    statementn

Where the first variable is the key and the second variable is the value (in the syntax above, I used the words key and value, but you could use an variable names)

Example #1:

puppy = {
      "breed": "Malteese",
      "color": "white",
      "eyes": "black"
}
for key, value in puppy.items():
      print(key, ":", value)

Example #2:

puppy = {
      "breed": "Malteese",
      "color": "white",
      "eyes": "black"
}
for x, y in puppy.items():
      print(x, ":", y)

Sample Output:

breed : Malteese  
color : white  
eyes : black

F.  sorted() function

You can use the sorted function in a for loop to sort the dictionary when you access it. 

Example #1 using the keys() method with the sorted function:

glossary={
    "dictionary":"Python data type that stores key:value pairs",
    "key": "value used to access data stored in the dictionary",
    "del": "command used to remove a key:value pair from the dictionary"}

for k in sorted(glossary.keys()):     
    print(k,":", glossary[k])

Sample Output:

del : command used to remove a key:value pair from the dictionary
dictionary : Python data type that stores key:value pairs
key : value used to access data stored in the dictionary

Example #2 using the values() method with the sorted function

glossary={
    "dictionary":"Python data type that stores key:value pairs",
    "key": "value used to access data stored in the dictionary",
    "del": "command used to remove a key:value pair from the dictionary"}

for v in sorted(glossary.values()):     
    print(v.title())

Sample Output:

Python Data Type That Stores Key:Value Pairs
Command Used To Remove A Key:Value Pair From The Dictionary
Value Used To Access Data Stored In The Dictionary

Example #3 using the sorted method with the dictionary

glossary={
    "dictionary":"Python data type that stores key:value pairs",
    "key": "value used to access data stored in the dictionary",
    "del": "command used to remove a key:value pair from the dictionary"}

for k in sorted(glossary):     
    print(k,":", glossary[k])

Sample Output

del : command used to remove a key:value pair from the dictionary
dictionary : Python data type that stores key:value pairs
key : value used to access data stored in the dictionary


Hands On #2 - Looping through Dictionaries

To see a video demonstration, watch: https://youtu.be/8UoX882fbno

1.  Open glossary.py and complete Try It Yourself, 6-4 on page 105.

2.  Create a new file named rivers.py.  Complete Try It Yourself 6-5 on page 105.

Sample Output - there are 2 dictionary values that are lists.

------------------Rivers & Countries-------------------------------
The Danube river flows through ['Germany', 'Austria', 'Slovakia', 'Hungary', 'Coratia', 'Serbia', 'Romania', 'Bulgaria', 'Moldova', 'Ukraine']
The Mississippi river flows through United States
The Amazon river flows through ['Brazil', 'Bolivia', 'Peru', 'Ecuador', 'Colombia', 'Venezuela', 'Guyana', 'Suriname', 'French Guiana']
------------------Rivers-------------------------------
Danube
Mississippi
Amazon
------------------Countries-------------------------------
['Germany', 'Austria', 'Slovakia', 'Hungary', 'Coratia', 'Serbia', 'Romania', 'Bulgaria', 'Moldova', 'Ukraine']
United States
['Brazil', 'Bolivia', 'Peru', 'Ecuador', 'Colombia', 'Venezuela', 'Guyana', 'Suriname', 'French Guiana']

IV. Nesting

A. Dictionaries inside lists.

You can create a list of dictionary items by including the dictionary name as an item in the list.

Syntax:   listName=[dictionaryName1, dictionaryName2, dictionaryNamen]

Example from the book of dictionaries inside a list:

alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}

aliens = [alien_0, alien_1, alien_2]

for alien in aliens:
       print(alien)

Sample Output:

{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}

Better example that begins with an empty list and adds aliens using a for loop (adapted from the textbook):

import random
# Make an empty list for storing aliens.
aliens = []

# Make 30 green aliens.
for alien_number in range(30):
    randPoints = random.randrange(1,100)
    new_alien = {'color': 'green', 'points': randPoints, 'speed': 'slow'}
    aliens.append(new_alien)

for alien in aliens[:10]:    
    print(alien)

Sample Output:

{'color': 'green', 'points': 11, 'speed': 'slow'}
{'color': 'green', 'points': 78, 'speed': 'slow'}
{'color': 'green', 'points': 99, 'speed': 'slow'}
{'color': 'green', 'points': 7, 'speed': 'slow'}
{'color': 'green', 'points': 73, 'speed': 'slow'}
{'color': 'green', 'points': 58, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 88, 'speed': 'slow'}
{'color': 'green', 'points': 69, 'speed': 'slow'}
{'color': 'green', 'points': 53, 'speed': 'slow'}

NOTE:  To make color and speed more random, you could do something like this:

import random
# Make an empty list for storing aliens.
aliens = []
color=["green","pink","purple","blue","orange"]
speed=["slow","medium","fast"]

# Make 30 green aliens.
for alien_number in range(30):
    randPoints = random.randrange(1,100)
    colorSub=random.randrange(0,5)
    newColor=color[colorSub]
    speedSub=random.randrange(0,3)
    newSpeed=speed[speedSub]
    new_alien = {'color': newColor, 'points': randPoints, 'speed': newSpeed}
    aliens.append(new_alien)

for alien in aliens[:10]:    
    print(alien)

Sample Output:

{'color': 'purple', 'points': 98, 'speed': 'slow'}
{'color': 'green', 'points': 72, 'speed': 'medium'}
{'color': 'purple', 'points': 45, 'speed': 'medium'}
{'color': 'orange', 'points': 37, 'speed': 'slow'}
{'color': 'orange', 'points': 77, 'speed': 'medium'}
{'color': 'green', 'points': 49, 'speed': 'medium'}
{'color': 'purple', 'points': 56, 'speed': 'medium'}
{'color': 'pink', 'points': 72, 'speed': 'fast'}
{'color': 'orange', 'points': 90, 'speed': 'medium'}
{'color': 'orange', 'points': 21, 'speed': 'fast'}

B.  Lists inside dictionaries

You can store lists inside dictionaries anytime you ant more than one value associated with a key in the dictionary.

Example from the book:

 # Store information about a pizza being ordered.
pizza = {
    'crust': 'thick',
    'toppings': ['mushrooms', 'extra cheese'],
    }

# Summarize the order.
print(f"You ordered a {pizza['crust']}-crust pizza "
    "with the following toppings:")

for topping in pizza['toppings']:
    print("\t" + topping)

Sample Output:

You ordered a thick-crust pizza with the following toppings:
               mushrooms
               extra cheese

C.  Dictionaries inside Dictionaries

You can associate a dictionary as the value stored by one key

Syntax:

dictionaryName={
       "key1": {
            "keya":"value",
            "keyb":"value",
            "keyc":"value",
            "keyn":"value",
       }
       "key2": {
            "keya":"value",
            "keyb":"value",
            "keyc":"value",
            "keyn":"value",
       }
       "key3": {
            "keya":"value",
            "keyb":"value",
            "keyc":"value",
            "keyn":"value",
       }
}

Example #1 from the book:

users = {
    'aeinstein': {
        'first': 'albert',
        'last': 'einstein',
        'location': 'princeton',
        },

    'mcurie': {
        'first': 'marie',
        'last': 'curie',
        'location': 'paris',
        },

    }

for username, user_info in users.items():
    print(f"\nUsername: {username}")
    full_name = f"{user_info['first']} {user_info['last']}"
    location = user_info['location']

    print(f"\tFull name: {full_name.title()}")
    print(f"\tLocation: {location.title()}")

Sample Output

Username: aeinstein
                 Full name: Albert Einstein
                 Location: Princeton

Username: mcurie
                 Full name: Marie Curie
                 Location: Paris

Example #2:

puppies = {
    'M1': {
        'breed':"Malteese",
        'age': '10 weeks',
        'sex': 'female',
        'price': 1000,
        },

    'M2': {
        'breed':"Malteese",        
        'age': '10 weeks',
        'sex': 'male',
        'price': 1000,
        },

    'Y1': {
        'breed':"Yorkie",        
        'age': '12 weeks',
        'sex': 'male',
        'price': 1200,
        },

    'MY1': {
        'breed':"Morkie",        
        'age': '12 weeks',
        'sex': 'female',
        'price': 1600,
        },        
}


for pup, info in puppies.items():
    print(f"\nPuppy: {info['breed']}")
    age =info['age']
    sex = info['sex']
    price = info['price']

    print(f"\tAge: {age}")
    print(f"\tSex: {sex}")
    print(f"\tPrice: ${price}")

Sample Output:

Puppy: Malteese
           Age: 10 weeks
           Sex: female
           Price: $1000

Puppy: Malteese
           Age: 10 weeks
           Sex: male
           Price: $1000

Puppy: Yorkie
           Age: 12 weeks
           Sex: male
           Price: $1200

Puppy: Morkie
           Age: 12 weeks
           Sex: female
           Price: $1600


Hands On #3 - Nesting Dictionaries and Lists

To see a video demonstration, watch:  https://youtu.be/LPdinFE_R7w

1.   Create 3 dictionaries and store them in a list, then print each one using a for loop.   (This is similar to the examples in part A above.).  Name the file dictionary_list.py

Partial Example - the trips list includes 3 dictionaries(destinations, accomodations and transportation)

trips=[destinations,accomodations,transportation]
for t in trips:
    print(t)

2.  Create at least 1 dictionary that includes a list.  Print the dictionary items and each item in the list.  (This is similar to the pizza exercise in part B above).  Name the file nested_list.py 

NOTE: If your rivers.py file has dictionaries with lists as values, you can copy it into this file and adjust the code to print out each item in the dictionary AND each item in the list.  If you have dictionary keys that have lists and some that do not have lists, you would need to code something like this:

rivers={
    "Danube":["Germany","Austria","Slovakia","Hungary", "Coratia", "Serbia","Romania","Bulgaria", "Moldova", "Ukraine"],
    "Mississippi":"United States",
    "Amazon":["Brazil","Bolivia","Peru","Ecuador","Colombia","Venezuela","Guyana", "Suriname", "French Guiana"]
}

for key, value in rivers.items():
    if type(value)==list:
        print(f"The {key.title()} river flows through: ")
        for v in value:
            print("\t\t\t\t",v)
    else:    
        print(f"The {key.title()} river flows through {value.title()}")

 

3.  Create a dictionary that includes a nested dictionary for each key. Print out the nested dictionary key:value pairs.  (This is similar to the puppy example above).  Name the file nested_dictionaries.py. 


Hands On #4 - Uploading to GitHub

To see a video demonstration, watch: https://youtu.be/6WkxIH2N6fU

1.  You should have the following files in your Chapter6 folder:

2.  Upload Chapter6 to GitHub

a.  Click the ... next to CIT228 Git and select the Changes menu, Stage all Changes command.

b.  In the Message window below Source Control, enter Chapter6 and then click the ... next to CIT228 Git and select the Commit menu,  Commit Staged command

c.  Display the menu next to the CIT228 Git folder by selecting ...  and select the Push command

d.  This will put all files and folders inside your CIT228/Chapter6 directory into your GitHub repository

3.  Open a web browser and go to your CIT228 repository.  Make sure the Chapter6 directory and files are there, then copy the URL and paste it into the lab assignment dropbox (you are done with the second part of your lab assignment!)