Skip to content

Week 9 - Dictionaries

Python Dictionaries

Lesson Objective:

  • Understand what dictionaries are and how they differ from lists.
  • Create and manipulate dictionaries using keys and values.
  • Utilize dictionary methods and operators.
  • Solve problems involving dictionaries, such as counting unique elements or filtering data.

Introduction to Dictionaries

  • Key Concept: A dictionary is a collection of key-value pairs where each key is unique.
  • Key Concept: A dictionary is based on a Hash Table datastructure, and therefore the keys must be immutable to ensure key hash-values don’t change.
  • Code Example: Creating a simple dictionary to store information about a student.
    1
    2
    3
    4
    5
    6
    student = {
        'name': 'Alice',
        'age': 22,
        'major': 'Computer Science'
    }
    print(student['name'])  # Outputs: Alice
    

Dictionaries vs. Lists

  • Key Concept: While lists use integer indices to access elements, dictionaries use keys, which can be any immutable type.
  • Code Example: Using a dictionary to map grades to students.
    1
    2
    grades = {'Alice': 'A', 'Bob': 'B', 'Charlie': 'C'}
    print(grades['Bob'])  # Outputs: B
    

Creating Dictionaries

  • Key Concept: Dictionaries can be created directly with key-value pairs or by using the dict() function.
  • Key Concept: The dict() function can also be used to clone a dictionary, though object in the dictionary values of cloned dictionaries could stll be the same.
  • Code Example: Using the dict() constructor to create a dictionary from a list of tuples.
    1
    2
    3
    list_of_tuples = [('apple', 3), ('banana', 6), ('cherry', 5)]
    fruit_counts = dict(list_of_tuples)
    print(fruit_counts)  # Outputs: {'apple': 3, 'banana': 6, 'cherry': 5}
    

The in Operator with Dictionaries

  • Key Concept: Use the in operator to check if a key exists in a dictionary.
  • Code Example: Checking if a key is in a dictionary.
    1
    2
    3
    country_codes = {'US': 1, 'IN': 91, 'JP': 81}
    if 'JP' in country_codes:
        print('Country code for Japan is:', country_codes['JP'])
    

Updating and Modifying Dictionarie

  • Key Concept: Adding, updating, or deleting items from a dictionary.
  • Code Example: Removing an entry and adding a new one.
    1
    2
    3
    4
    phone_book = {'Alice': '555-1234', 'Bob': '555-5678'}
    del phone_book['Alice']  # Removes Alice
    phone_book['Charlie'] = '555-8765'  # Adds Charlie
    print(phone_book)  # Outputs: {'Bob': '555-5678', 'Charlie': '555-8765'}
    

Looping through Dictionaries

  • Key Concept: Use loops to iterate over keys and values.
  • Code Example: Looping over keys and values in a dictionary.
    1
    2
    3
    color_codes = {'red': '#FF0000', 'green': '#00FF00', 'blue': '#0000FF'}
    for color, code in color_codes.items():
        print(f'{color}: {code}')
    

Counting Items with Dictionaries

  • Key Concept: Use a dictionary as a counter to count occurrences of elements.
  • Code Example: Counting how many times each character appears in a string.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    def count_characters(string):
        counts = {}
        for char in string:
            if char in counts:
                counts[char] += 1
            else:
                counts[char] = 1
        return counts
    
    print(count_characters('abracadabra'))
    

Using Dictionaries for Memoization

  • Key Concept: Store precomputed results in a dictionary to improve performance (e.g., Fibonacci).
  • Code Example: Memoized Fibonacci function.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    memo = {0: 0, 1: 1}
    
    def fibonacci(n):
        if n in memo:
            return memo[n]
        memo[n] = fibonacci(n-1) + fibonacci(n-2)
        return memo[n]
    
    print(fibonacci(10))  # Outputs: 55
    

Exercises:

Exercise 1: Word Frequency Counter
Write a function that takes a sentence as input and returns a dictionary where the keys are words, and the values are the number of times each word appears.

Exercise 2: Student Grades
Create a dictionary to store the names of students and their grades. Write a function that accepts this dictionary and returns the name of the student with the highest grade.

Exercise 3: Filtering Long Words
Given a list of words, create a function that returns a dictionary where the keys are the lengths of the words and the values are lists of words of that length.