AI summary by TwinMind

Lecture 14: Dictionaries

MIT OpenCourseWare

1h 18m 5s

Motivation for Dictionaries

  • Problem: storing student information using lists becomes messy
  • Previous approach: separate lists for names and grades, requiring index tracking
    • Need to pass multiple lists to functions
    • Must maintain index correspondence across lists
    • Complex mutation operations when adding/removing students
  • Alternative approach: master list with sublists
    • Still complex with nested data structures
    • Hard to read and maintain code

Dictionary Basics

  • New compound data type for mapping custom keys to values
  • Entry = key-value pair mapping
  • Created using curly braces {}
  • Empty dictionary: {}
  • Single entry: {4: 16} (key 4 maps to value 16)
  • Multiple entries separated by commas
  • Example: {'Anna': 'B', 'Matt': 'A', 'John': 'B', 'Katie': 'A'}

Dictionary Operations

Lookup Values

  • Syntax: dictionary[key] (similar to list indexing)
  • Example: grades['John'] returns 'B'
  • KeyError raised if key doesn't exist
  • Cannot reverse lookup (value to key) without custom code
  • Values can be duplicated, keys cannot

Adding/Modifying Entries

  • Add new entry: grades['Grace'] = 'A'
  • Modify existing: grades['Grace'] = 'C' (overwrites)
  • All operations mutate original dictionary

Deleting Entries

  • Use del function: del grades['Anna']
  • Completely removes key-value pair

Checking Key Existence

  • Use in operator: 'John' in grades returns True
  • Only checks keys, not values
  • Returns boolean

Iteration Methods

Keys Only

  • dictionary.keys() returns dict_keys object (iterable)
  • Can cast to list: list(grades.keys())
  • For loop: for k in grades.keys()

Values Only

  • dictionary.values() returns dict_values object
  • Can cast to list: list(grades.values())

Key-Value Pairs

  • dictionary.items() returns dict_items object
  • Each element is tuple of (key, value)
  • Preferred method: for k, v in grades.items()
  • Provides access to both key and value simultaneously

Dictionary Properties

Mutability and Aliasing

  • Dictionaries are mutable objects
  • Assignment creates alias: d1 = d2
  • Use d.copy() for actual copy

Key Restrictions

  • Keys must be unique (no duplicates)
  • Keys must be immutable/hashable: int, float, string, tuple, bool
  • Cannot use mutable objects as keys: list, dictionary

Value Flexibility

  • Values can be any type: int, float, string, list, tuple, dictionary
  • Values can be duplicated
  • No restrictions on value types

Hash Function Explanation

  • Python uses hash function to store dictionary entries
  • Hash function converts key to memory location number
  • Key → Hash Function → Memory Location → Store Value
  • Mutable keys problematic: if key changes, hash changes, can't find original value
  • Example: list as key could be modified, breaking lookup

Advanced Dictionary Usage

Nested Dictionaries

  • Values can be dictionaries themselves
  • Example: student data with nested grade categories
  • Access pattern: grades['Anna']['mq'][0] for first micro quiz score

Complex Data Structures

  • Master dictionary mapping students to grade dictionaries
  • Each student maps to dictionary with 'mq', 'PS', 'fin' keys
  • Enables clean, hierarchical data organization

Word Frequency Analysis Example

Step 1: Generate Frequency Dictionary

  • Convert song string to lowercase
  • Split into word list using split()
  • Create empty dictionary
  • Iterate through words:
    • If word exists: increment count
    • If new word: add with count 1
  • Result: dictionary mapping words to frequencies

Step 2: Find Most Frequent Words

  • Get maximum value from dictionary.values()
  • Iterate through dictionary.items()
  • Collect all keys with maximum value
  • Return tuple of (word_list, max_frequency)

Step 3: Find Words Above Threshold

  • Use previous function to find highest frequency words
  • Mutate dictionary by removing found words using del
  • Repeat until remaining frequencies below threshold
  • Build result list of (words, frequency) tuples
  • Demonstrates function reuse and mutability

Key Concepts Reinforced

  • Lists: ordered sequences with integer indices 0, 1, 2...
  • Dictionaries: unordered mappings with custom keys
  • No guaranteed order in dictionaries (except insertion order in recent Python)
  • Efficient lookup operations compared to list searching
  • Powerful for data organization and frequency counting

TwinMind

Get summaries like this for your own meetings

TwinMind takes notes in the background during meetings, lectures, and calls, then writes the summary for you.

Free plan to get started

No bot joins your calls

Phone, desktop & Chrome apps

Your next meeting, summarized like this

TwinMind listens in the background and turns meetings, lectures, and calls into searchable notes you can chat with. Start free.

Available on phone, desktop & Chrome

Your next meeting, summarized like this

TwinMind listens in the background and turns meetings, lectures, and calls into searchable notes you can chat with. Start free.

Available on phone, desktop & Chrome

Your next meeting, summarized like this

TwinMind listens in the background and turns meetings, lectures, and calls into searchable notes you can chat with. Start free.

Available on phone, desktop & Chrome