Fiveable

๐ŸIntro to Python Programming Unit 10 Review

QR code for Intro to Python Programming practice questions

10.5 Nested dictionaries and dictionary comprehension

๐ŸIntro to Python Programming
Unit 10 Review

10.5 Nested dictionaries and dictionary comprehension

Written by the Fiveable Content Team โ€ข Last updated September 2025
Written by the Fiveable Content Team โ€ข Last updated September 2025
๐ŸIntro to Python Programming
Unit & Topic Study Guides

Nested dictionaries in Python allow for complex data organization, enabling hierarchical structures like employee records or product catalogs. They're created by nesting dictionaries within other dictionaries, accessed using key sequences, and can be modified or retrieved with various methods.

Dictionary comprehension offers a concise way to create dictionaries from existing iterables. This efficient technique allows for filtering and transforming data in a single line, making it a powerful tool for dictionary creation and manipulation in Python programming.

Nested Dictionaries

Nested dictionaries for hierarchical data

  • Nested dictionaries contain dictionaries as values within an outer dictionary
    • Enables representation of hierarchical or multi-level data structures (employee records, product catalogs)
  • Create a nested dictionary by defining dictionaries as values for keys in the outer dictionary
    • employee_info = {
          'John': {
              'department': 'Sales',
              'salary': 50000
          },
          'Emily': {
              'department': 'Marketing',
              'salary': 60000
          }
      }
      
  • Access values in a nested dictionary using a sequence of keys
    • Syntax: dictionary[outer_key][inner_key]
    • employee_info['John']['department'] retrieves John's department (Sales)
  • Modify values by assigning a new value using the key sequence
    • employee_info['Emily']['salary'] = 65000 updates Emily's salary
  • Use the get() method to provide a default value if a key is missing and avoid KeyError
    • employee_info.get('Michael', {}).get('salary', 0) returns 0 if 'Michael' or 'salary' key doesn't exist

Accessing nested dictionary values

  • Retrieve values from a nested dictionary by specifying the sequence of keys
    • Access outer dictionary key, then inner dictionary key (product_catalog['electronics']['smartphones'])
  • Update values by assigning a new value to the specific key sequence
    • student_grades['Alice']['Math'] = 90 updates Alice's Math grade
  • Check if a key exists before accessing to avoid KeyError
    • if 'John' in employee_info and 'department' in employee_info['John']:
          department = employee_info['John']['department']
      
  • Use get() method to provide a default value if a key is missing
    • product_price = product_catalog.get('books', {}).get('fiction', 0) returns 0 if 'books' or 'fiction' key doesn't exist
  • Iteration through nested dictionaries allows for efficient data processing

Dictionary Comprehension

Dictionary comprehension for efficiency

  • Concise way to create dictionaries based on existing iterables (lists, tuples)
  • Syntax: {key_expr: value_expr for item in iterable if condition}
    • key_expr determines the keys, value_expr determines the values
    • item represents each element in the iterable
    • Optional condition filters items to include
  • Create a dictionary from a list of names, with lengths as values:
    • names = ['Alice', 'Bob', 'Charlie']
      name_lengths = {name: len(name) for name in names}
      # name_lengths = {'Alice': 5, 'Bob': 3, 'Charlie': 7}
      
  • Create a nested dictionary using dictionary comprehension:
    • subjects = ['Math', 'Science', 'English']
      student_scores = {student: {subject: 0 for subject in subjects} for student in ['John', 'Emily']}
      
  • Filter items based on a condition:
    • numbers = [1, 2, 3, 4, 5]
      even_squares = {x: x2 for x in numbers if x % 2 == 0}
      # even_squares = {2: 4, 4: 16}
      

Advanced Dictionary Concepts

  • Nesting allows for complex data organization within dictionaries
  • Comprehension provides a concise way to create dictionaries
  • Data structures like dictionaries offer flexible key-value mapping
  • Dictionaries are fundamental for organizing and manipulating data efficiently