Python Classroom
  • Introduction
  • About Python Classroom
  • Python Cloud Options
    • CS50 IDE
      • CS50 IDE Overview
      • CS50 IDE and Python
      • CS50 IDE Debugging
      • CS50 IDE Shortcuts
      • Linux Bash Shell
      • Vim Mode
        • Vim Tutorial
    • CS50 Sandbox
    • PythonAnywhere
    • Repl.it
  • Python Curriculum Map
    • Pedagogy
      • Python Professional Development
      • Teaching Tips
      • Assessment Tips
      • Rubrics
      • Activities
        • Picture Activity
        • Map Activity
        • Crossing the Bridge
        • NIM
        • Mastermind
        • Cards
          • Card Deck Algorithms
          • Sorting Cards
        • River Crossing
          • Jealous Boyfriends
          • Cannibals and Priests
          • Family
          • Police and the Thief
          • Humans and Monkeys
          • Moving Money
        • Crossing the River
        • Traveling Salesperson
        • Logic Problems
        • CIA Crack the Code
        • IQ Test
        • Puzzles
    • AP Computer Science Principles Framework
  • Python Philosphy
    • How to Practice Python
  • microbit
  • Turtle Graphics
    • Turtle Examples
    • Turtle Activities
    • Turtle Maze Problems
    • Turtle Graphics with loops
    • Turtle Snake
    • Turtle Graphics with Conditionals
  • Output
    • Output Examples
    • Output Mistakes
  • Variables
    • Variable Data Type Examples
    • Variable Role Examples
    • Variables Mistakes
    • Variables Problems
  • Math
    • Math Examples
    • Math Mistakes
    • Math Problems
    • Math Self Check
  • Input
    • Input Examples
    • Input Mistakes
    • Input Problems
  • Decisions
    • if
      • if Examples
      • if Mistakes
      • if Problems
    • if else
      • if else Examples
      • if else Problems
      • if / if else Problems
    • if elif else
      • if elif else Examples
      • if elif else Problems
    • nested if
      • nested if Examples
      • nested if Problems
    • Logical Operators
      • Logical Operators Examples
    • Adventure Game Project
  • Loops
    • while loop - count up
      • Examples
      • Problems
    • while loop - countdown
      • Examples
      • Problems
    • while loop - sentinel value
      • Problems
    • while loop - sentinel menu
      • Problems
    • for loop - range (one argument)
      • Examples
      • Problems
    • for loop - range (two arguments)
      • Problems
    • for loop - range (three arguments)
      • Problems
  • Lists
    • Lists - Numbers
      • Problems
    • Lists - Strings
      • Problems
      • Shopping Project
  • Dictionaries
  • String Methods
  • Functions
    • Variable Scope
    • Functions - no parameters
    • Functions - one parameter
    • Functions - return
    • Functions - lists
  • Files
  • Classes
    • Inheritance
  • Python Projects
    • Adventure Game
    • Restaurant Project
    • Trivia Game
    • Family Tree Project
  • Raspberry Pi
    • Raspberry Pi Models
    • Raspberry Pi Setup
  • Roblox
  • Glossary
Powered by GitBook
On this page
  • Objective
  • Introductory Problem
  • Dictionaries
  • Dictionary Functions and Operations
  • Examples
  • Example 1
  • Example 2
  • Example 3
  • Example 4

Was this helpful?

Dictionaries

Objective

After working through this lesson, you’ll be able to

  • Write Python code using dictionaries.

Introductory Problem

Create a list named friends of 3 of your friends. Create another list named towns of the 3 towns that they live in. Print these lists.

intro.py
done = False
friends = ["Sofia", "Alex", "Sam"]
towns = ["Paterson", "Passaic", "Clifton"]

while not done:
    print("Menu")
    print("I - Introductory Problem")
    print("Q - Quit")
    choice = input("Choice: ")
    if choice == "I":
        print("Introductory Problem")
        for i in range(len(friends)):
            print(friends[i])
        for i in range)len(towns)):
            print(towns[i])
    elif choice == "Q":
        print("Exiting Game!")
        done = True

Dictionaries

A dictionary is a container that keeps associations between keys and values. Every key in a dictionary has an associated value. Keys are unique but a value may be associated with several keys. The dictionary structure is also known as a map or a hash table because it maps a unique key to a value.

Dictionary Functions and Operations

d = {}

Creates a new empty dictionary.

d = {k1:v1,k2:v2,... , kn:vn}

Creates a new dictionary called d that contains the initial items provided. Each item consists of a key (k) and value (v) separated by a colon.

d[key]

Returns the value associated with the given key.

len(d)

Returns the number of items in dictionary d.

key in d

key not in d

The in operator is used to test if a key is in the dictionary.

d[key] = value

Adds a new key/value item to the dictionary if the key does not exist. If the key does exist, it modifies the value associated with the key.

d.get(key)

Returns the value associated with the given key.

d.pop(key)

Removes the key and its associated value from the dictionary.

d.keys()

Returns a sequence containing all keys of the dictionary.

d.values()

Returns a sequence contains all the values of the dictionary.

for key in d:

print(key)

Iterates over keys in a dictionary.

Examples

Example 1

Create a dictionary called d with 3 of your friends names and the towns they live in. Print the dictionary using a for loop.

example1.py
done = False
d = {"Sofia":"Paterson", "Alex":"Passaic", "Sam":"Clifton"}

while not done:
    print("Menu")
    print("E1 - Example 1")
    print("Q - Quit")
    choice = input("Choice: ")
    if choice == "E1":
        print("Example 1")
        print("Key\t"Value")
        for key in d:
            print(key, "\t", d[key])
    elif choice == "Q":
        print("Exiting Game!")
        done = True

Example 2

You are riding the bus and make new friends and you want to add them to your dictionary. Rita lives in West Milford and Karla lives in Haledon. Add these friends to your dictionary and print.

example2.py
done = False
d = {"Sofia":"Paterson", "Alex":"Passaic", "Sam":"Clifton"}

while not done:
    print("Menu")
    print("E2 - Example 2")
    print("Q - Quit")
    choice = input("Choice: ")
    if choice == "E1":
        print("Example 2")
        d["Rita"] = "West Milford"
        d["Karla"] = "Haledon"
        print("Key\t"Value")
        for key in d:
            print(key, "\t", d[key])
    elif choice == "Q":
        print("Exiting Game!")
        done = True

Example 3

Sadly, your friend Sofia moves away never to be seen or heard from again. Remove her from your dictionary. Print how many friends you have left.

example3.py
done = False
d = {"Sofia":"Paterson", "Alex":"Passaic", "Sam":"Clifton"}

while not done:
    print("Menu")
    print("E3 - Example 3")
    print("Q - Quit")
    choice = input("Choice: ")
    if choice == "E1":
        print("Example 3")
        d.pop("Sofia")
        print(len(d))
    elif choice == "Q":
        print("Exiting Game!")
        done = True

Example 4

Your friend wants to quiz you on what towns your friends live in. Print the friend’s name and then ask the user what town he/she lives in. If the user gets the answer correct, print “Correct!”. Else print “Incorrect”.

example4.py
done = False
d = {"Sofia":"Paterson", "Alex":"Passaic", "Sam":"Clifton"}

while not done:
    print("Menu")
    print("E4 - Example 4")
    print("Q - Quit")
    choice = input("Choice: ")
    if choice == "E1":
        print("Example 4")
        for key in d:
            print("Where does",key,"live?")
            town = input(":: ")
            if d[key] == town:
                print("Correct!")
            else:
                print("Incorrect!")
    elif choice == "Q":
        print("Exiting Game!")
        done = True

PreviousShopping ProjectNextString Methods

Last updated 6 years ago

Was this helpful?