10.5 Nested dictionaries and dictionary comprehension

3 min readjune 24, 2024

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

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

Top images from around the web for Nested dictionaries for hierarchical data
Top images from around the web for Nested dictionaries for hierarchical data
  • contain dictionaries as values within an outer dictionary
    • Enables representation of hierarchical or multi-level (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()](https://www.fiveableKeyTerm:get())
    method to provide a default value if a key is missing and avoid
    [KeyError](https://www.fiveableKeyTerm: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 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
  • 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 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 :
    • 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: x**2 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
  • provides a concise way to create dictionaries
  • Data structures like dictionaries offer flexible
  • Dictionaries are fundamental for organizing and manipulating data efficiently

Key Terms to Review (23)

Accessing: Accessing refers to the ability to retrieve, read, or manipulate data stored in a data structure, such as a dictionary. It is a fundamental operation that allows users to interact with and extract information from these data containers.
Comprehension: Comprehension is the ability to understand and make sense of information, ideas, or concepts. It involves actively engaging with and interpreting the meaning of what is being learned or communicated.
Data Structures: Data structures are the fundamental ways in which data is organized, stored, and manipulated within a computer program. They provide efficient methods for accessing, processing, and managing information, enabling programs to perform complex tasks effectively.
Deleting: Deleting refers to the act of removing or erasing data from a data structure, such as a dictionary or list, in the context of programming. It involves the permanent removal of an element or key-value pair from the data structure.
Dict: A dictionary (dict) in Python is a collection of key-value pairs, where each key is unique and maps to a corresponding value. Dictionaries are a fundamental data structure in Python that allow for efficient storage and retrieval of data, making them a crucial tool in various programming tasks, including data analysis, data science, and problem-solving.
Dictionary comprehension: Dictionary comprehension is a concise way to create dictionaries in Python using a single line of code. It follows the format {key: value for item in iterable if condition}.
Dictionary comprehension: Dictionary comprehension is a concise way to create dictionaries in Python using a single line of code, allowing for the transformation and filtering of data in a readable manner. This technique combines looping and conditionals into one expression, making it efficient and clean, especially when generating dictionaries from existing iterable data like lists or other dictionaries.
Get(): The get() method is a fundamental operation in Python that allows you to retrieve the value associated with a specific key in a dictionary. It provides a convenient way to access and extract data from a dictionary, making it a crucial tool in working with dictionaries, which are widely used data structures in Python.
Hierarchical Data: Hierarchical data refers to information that is organized in a tree-like structure, where data is arranged in a nested, parent-child relationship. This type of data structure allows for efficient storage and retrieval of complex information, making it a valuable tool in various applications, including database management and data analysis.
In: The term 'in' is a preposition that is used to indicate location, time, or inclusion within a specific context. It is a fundamental part of the English language and plays a crucial role in various programming concepts, including string manipulation, list operations, dictionary usage, and control flow structures.
Items(): The items() method in Python dictionaries returns a view object that displays a list of dictionary's (key, value) tuple pairs. It provides a way to iterate over both the keys and values of a dictionary simultaneously, making it a useful tool for working with dictionaries.
Iteration: Iteration is the process of repeating a set of instructions or operations multiple times in a computer program or algorithm. It is a fundamental concept in programming that allows for the execution of a block of code repeatedly until a specific condition is met.
Key-Value Mapping: Key-value mapping is a fundamental data structure in programming that associates a unique key with a corresponding value. It allows for efficient storage and retrieval of data by providing a direct relationship between the key and its associated value.
Key-Value Pairs: Key-value pairs are the fundamental building blocks of dictionaries in Python. They consist of a unique key, which acts as an identifier, and an associated value that represents the data stored under that key.
KeyError: A KeyError is a specific type of error in Python that occurs when you try to access a dictionary using a key that doesn't exist. This error highlights the importance of key management in dictionaries, which are collections of key-value pairs. Understanding how KeyError arises can help in properly handling exceptions and ensuring that dictionary operations are executed without interruption.
Len(): The len() function is a built-in function in Python that returns the length or count of elements in a given object, such as a string, list, tuple, or dictionary. It is a fundamental operation that is widely used across various programming topics in Python.
List: A list in Python is an ordered collection of items, where each item can be of a different data type. Lists are one of the most fundamental and versatile data structures in the Python programming language, allowing you to store and manipulate multiple values in a single variable.
Nested dictionaries: A nested dictionary is a dictionary within another dictionary. It allows for hierarchical data structures where values can themselves be dictionaries.
Nested Dictionaries: Nested dictionaries, also known as dictionaries within dictionaries, are a data structure in Python where the values of a dictionary can be other dictionaries. This allows for the creation of complex, hierarchical data structures that can represent more intricate relationships and information.
Nesting: Nesting refers to the practice of placing one or more elements, such as loops, control structures, or data structures, within another element of the same type. This concept is fundamental in programming and allows for the creation of more complex and sophisticated algorithms and data representations.
Not in: The 'not in' operator is a logical operator used to check if a value is not present in a sequence, such as a list, tuple, or string. It is the opposite of the 'in' operator, which checks if a value is present in a sequence.
Sorted(): The sorted() function in Python is a built-in function that returns a new sorted list from the elements of any iterable (such as a list, tuple, or string). It allows you to sort the elements in ascending order by default, or in descending order if specified. The sorted() function is a powerful tool for organizing and manipulating data in Python.
Updating: Updating is the process of modifying or changing the existing information or data in a data structure, such as a dictionary, to reflect new or altered values. It involves replacing the previous value associated with a specific key in the dictionary with a new value.
© 2024 Fiveable Inc. All rights reserved.
AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.