Dictionaries¶

Introduction to Dictionaries¶

Dictionaries are a type of data structure in Python. A data structure is a structure, like a list or array, that holds data in some sort of way.

In a list, the structure is that data is individually stored in elements, which can then be accessed using an index.

A dictionary is slightly different in terms of structure. A dictionary has keys, which can be a number, string, or other data type, which correspond to values, which is the value held by the specific key. When compared to lists, the keys are like the indices, while the values are like the value of the element at the specific index.

Basic Dictionary Examples¶

Below is an example that compares lists and dictionaries:

In [ ]:
# Declaring a basic list
basic_list = [1, 2, 3, 4]
# Declaring a basic dictionary
basic_dict = {0:1, 1:2, 2:3, 3:4}

# Accessing an element in a list
print(f"List value: {basic_list[2]}")
# Accessing a value in a dictionary
print(f"Dictionary value: {basic_dict[2]}")
List value: 3
Dictionary value: 3

A dictionary can have strings for keys.

In [21]:
# A dictionary where keys are cities and values are the states they're in
city_state = {'Seattle':'Washington', 'Portland':'Oregon', 'New York':'New York'}
# Accessing a value in the dictionary
print(f"Seattle is in {city_state['Seattle']}.")
# Adding a key-value pair to the dictionary
city_state['San Francisco'] = 'California'
# Printing the new key-value pair
print(f"San Francisco is in {city_state['San Francisco']}.")
Seattle is in Washington.
San Francisco is in California.

You can iterate through a dictionary using a for loop.

In [23]:
for city in city_state:
    print(f"City is {city}")
    print(f"State is {city_state[city]}")
    print()
City is Seattle
State is Washington

City is Portland
State is Oregon

City is New York
State is New York

City is San Francisco
State is California

A key in a dictionary can hold multiple values.

In [24]:
# A dictionary of species in nature, grouped by species group
nature_species = {'fungus': ['moral', 'death cap', 'webcap', 'chanterelle', 'oyster'],
                    'tree': ['pine', 'oak', 'maple', 'fir'],
                    'insect': ['lady beetle', 'luna moth', 'monarch butterfly', 'mason bee'],
                    'mammal': ['white-tailed deer', 'grizzly bear', 'mountain lion', 'North American beaver'],
                    'bird': ['red cardinal', 'barn owl', 'crow', 'song sparrow']}

for species_group in nature_species:
    for species in nature_species[species_group]:
        print(f"{species} is a {species_group}")
moral is a fungus
death cap is a fungus
webcap is a fungus
chanterelle is a fungus
oyster is a fungus
pine is a tree
oak is a tree
maple is a tree
fir is a tree
lady beetle is a insect
luna moth is a insect
monarch butterfly is a insect
mason bee is a insect
white-tailed deer is a mammal
grizzly bear is a mammal
mountain lion is a mammal
North American beaver is a mammal
red cardinal is a bird
barn owl is a bird
crow is a bird
song sparrow is a bird

Creating Dictionaries with zip()¶

Dictionaries can be created using the zip() function. The zip() function lets you pair together multiple iterables, like lists. If you zip two lists, it will make a dictionary.

In [26]:
# List for keys
numbers_list = [1, 2, 3, 4]
# List for values
letters_list = ['a', 'b', 'c', 'd']

# Creating the dictionary using zip()
zip_dict = dict(zip(numbers_list, letters_list))
print(f'Zipped dictionary: {zip_dict}')
Zipped dictionary: {1: 'a', 2: 'b', 3: 'c', 4: 'd'}

More Dictionary Examples¶

This example calculates the final grade average for the students in BDS 310. Assignments are worth 70%, quizzes are worth 20%, and participation is worth 10%.

Disclaimer: This data is made-up.

In [27]:
def calculate_grade_average(grade_dict):
    # Variable to store average grade
    avg_grade = 0

    # Iterate through the grade categories to calculates averages
    for category in grade_dict:
        # Calculate average for category
        avg = sum(grade_dict[category])/len(grade_dict[category])

        # Add weighted grade value for the specific category to the total average
        if category == 'Assignments':
            avg_grade += avg * 0.7
        elif category == 'Quizzes':
            avg_grade += avg * 0.2
        else:
            avg_grade += avg * 0.1

    # Return the average final grade
    return avg_grade

# An examples BDS 310 grades dictionary
bds310_grades = {'Assignments': [80, 94, 99, 62, 89],
                  'Quizzes': [72, 90, 95, 47, 82],
                  'Participation': [90, 100, 100, 70, 100]}

print(f"The average final grade for BDS310 is {calculate_grade_average(bds310_grades)}.")
The average final grade for BDS310 is 84.0.

This example searches a dictionary for a value and returns True if it's found and False otherwise.

In [28]:
def value_search (dict, target):
    # Iterate through each key
    for key in dict:
        # Iterate through each value in the key
        for value in dict[key]:
            # Return True if the target value is present
            if value == target:
                return True
            
    # Return False if the target value isn't present
    return False

# An example dictionary to search
search_dict = {'shape': ['circle', 'square', 'diamond', 'triangle'],
                'color': ['purple', 'blue', 'green', 'pink', 'red'],
                'size': ['small', 'medium', 'large']}

print(f"'medium' is in the dictionary: {value_search(search_dict, 'medium')}")
print(f"'yellow' is in the dictionary: {value_search(search_dict, 'yellow')}")
'medium' is in the dictionary: True
'yellow' is in the dictionary: False

This example has a function to print a report of the weather information for November 28, 2025 of a chosen area from a dictionary of various areas in the Pacific Northwest and a function to calculate a chosen average statistic for the overall dictionary.

The included weather information is:

  • Temperature in Fahrenheit
  • Precipitation in inches
  • Wind in mph
In [29]:
def print_weather_report(weather_dict, location):
    # Print out report introduction
    print(f"--- {location} Weather Report ---")
    print()

    # Iterate through the weather statistics for the location
    for stat in weather_dict[location]:
        # Print the weather statistic for each statistic category
        if stat == 'Temperature':
            print(f"The temperature in {location} is {weather_dict[location][stat]} degrees Fahrenheit.")
        elif stat == 'Precipitation':
            print(f"The precipitation in {location} is {weather_dict[location][stat]} inches.")
        else:
            print(f"The wind speed in {location} is {weather_dict[location][stat]} mph.")

    # Print report exit
    print()
    print("--- That's all for the weather report! ---")

def calculate_avg_stat (weather_dict, stat):
    # Make a list for all the selected statistics
    stats = []

    # Iterate through the locations in the dictionary
    for location in weather_dict:
          # Add the specific statistic for the location to the statistics list
          stats.append(weather_dict[location][stat])
    
    # Calculate the overall statistics average
    avg = sum(stats)/len(stats)
    # Return the statistic average
    return avg

# An example weather dictionary for Pacific Northwest locations
weather_dict = {'Seattle, Washington': {'Temperature': 51, 'Precipitation': 0 , 'Wind': 6},
                'Portland, Oregon': {'Temperature': 53, 'Precipitation': 0.4, 'Wind': 5},
                'Vancouver, British Columbia': {'Temperature': 49, 'Precipitation': 0, 'Wind': 5},
                'Spokane, Washington': {'Temperature': 43, 'Precipitation': 0.15, 'Wind': 6},
                'Eugene, Oregon': {'Temperature': 55, 'Precipitation': 0, 'Wind': 3},
                'Bend, Oregon': {'Temperature': 47, 'Precipitation': 0, 'Wind': 8}}

print_weather_report(weather_dict, 'Seattle, Washington')
print()
print(f"The average precipitation for these cities is {round(calculate_avg_stat(weather_dict, 'Precipitation'), 2)}.")
--- Seattle, Washington Weather Report ---

The temperature in Seattle, Washington is 51 degrees Fahrenheit.
The precipitation in Seattle, Washington is 0 inches.
The wind speed in Seattle, Washington is 6 mph.

--- That's all for the weather report! ---

The average precipitation for these cities is 0.09.