Skip to ContentGo to accessibility pageKeyboard shortcuts menu
OpenStax Logo
Introduction to Python Programming

10.5 Nested dictionaries and dictionary comprehension

Introduction to Python Programming10.5 Nested dictionaries and dictionary comprehension

Learning objectives

By the end of this section you should be able to

  • Explain the structure of nested dictionaries.
  • Use dictionary comprehension to create a dictionary object.

Nested dictionaries

As described before, Python dictionaries are a type of data structure that allows for storing data in key-value pairs. Nested dictionaries are dictionaries that are stored as values within another dictionary. Ex: An organizational chart with keys being different departments and values being dictionaries of employees in a given department. For storing employee information in a department, a dictionary can be used with keys being employee IDs and values being employee names. The tables below outline the structure of such nested dictionaries and how nested values can be accessed.

Example 10.4

Defining nested dictionaries and accessing elements

Defining nested dictionaries
company_org_chart = {
  "Marketing": {
    "ID234": "Jane Smith"
  },
  "Sales": {
    "ID123": "Bob Johnson",
    "ID122": "David Lee"
  },
  "Engineering": {
    "ID303": "Radhika Potlapally",
    "ID321": "Maryam Samimi"
  }
}
Table 10.8
Accessing nested dictionary items
print(company_org_chart["Sales"]["ID122"])
print(company_org_chart["Engineering"]["ID321"])
David Lee
Maryam Samimi
Table 10.9

Concepts in Practice

Nested dictionary structure

1.
What is a nested dictionary in Python?
  1. A dictionary that contains only integers as keys and values.
  2. A dictionary that contains another dictionary as a value.
  3. A dictionary that contains only strings as keys and values.
  4. A dictionary that contains only lists as keys and values.
2.
How can a value be accessed in a nested dictionary in Python?
  1. by using the key of the outer dictionary
  2. by using the key of the inner dictionary
  3. By using both the keys of the outer and inner dictionaries
3.
What is the syntax for creating a nested dictionary in Python?
  1. {key: value}
  2. {key1: {key2: value}}
  3. {key: {value: key2}}

Dictionary comprehension

Dictionary comprehension is a concise and efficient way to create a dictionary in Python. With dictionary comprehension, elements of an iterable object are transformed into key-value pairs. The syntax of dictionary comprehension is similar to list comprehension, but instead of using square brackets, curly braces are used to define a dictionary.

Here is a general syntax for dictionary comprehension:

Syntax for dictionary comprehension

    {key_expression: value_expression for element in iterable}

Checkpoint

Squares of numbers

Concepts in Practice

Dictionary comprehension

4.
What is the output of the following code?
numbers = [1, 2, 3, 4, 5]
my_dict = {x: x**2 for x in numbers if x % 2 == 0}
print(my_dict)
  1. {1: 1, 3: 9, 5: 25}
  2. {2: 4, 4: 16}
  3. {1: 2, 2: 4, 3: 6, 4: 8, 5: 10}
5.
What is the output of the following dictionary comprehension?
names = ["Alice ", "Bob ", "Charlie "]
name_lengths = {name: len(name) for name in names}
print(name_lengths)
  1. { "Alice ": 5, "Bob ": 3, "Charlie ": 7}
  2. {5: "Alice ", 3: "Bob ", 7: "Charlie "}
  3. { "A ": 5, "B ": 3, "C ": 7}
6.

What is the output of the following dictionary comprehension?

my_dict = {i: i**2 for i in range(4)}
print(my_dict)
  1. {0: 0, 1: 1, 2: 4, 3: 9}
  2. {0: 0, 1: 1, 2: 4}
  3. {1: 1, 2: 4, 3: 9}

Try It

Product prices

Suppose you have a dictionary of product prices, where the keys are product names and the values are their respective prices in dollars. Write a Python program that uses dictionary comprehension to create a new dictionary that has the same keys as the original dictionary, but the values are the prices in euros. Assume that the exchange rate is 1 dollar = 0.85 euros.

Try It

Restructuring the company data

Suppose you have a dictionary that contains information about employees at a company. Each employee is identified by an ID number, and their information includes their name, department, and salary. You want to create a nested dictionary that groups employees by department so that you can easily see the names and salaries of all employees in each department. Write a Python program that when given a dictionary, employees, outputs a nested dictionary, dept_employees, which groups employees by department.

    Input:
    employees = {
      1001: {"name": "Alice", "department": "Engineering", "salary": 75000},
      1002: {"name": "Bob", "department": "Sales", "salary": 50000},
      1003: {"name": "Charlie", "department": "Engineering", "salary": 80000},
      1004: {"name": "Dave", "department": "Marketing", "salary": 60000},
      1005: {"name": "Eve", "department": "Sales", "salary": 55000}
    }
    Resulting dictionary:
    
    {
    "Engineering": {1001: {"name": "Alice", "salary": 75000}, 1003: {"name": 
    "Charlie", "salary": 80000}},
    "Sales": {1002: {"name": "Bob", "salary": 50000}, 1005: {"name": "Eve", 
    "salary": 55000}},
    "Marketing": {1004: {"name": "Dave", "salary": 60000}}
    }
Citation/Attribution

This book may not be used in the training of large language models or otherwise be ingested into large language models or generative AI offerings without OpenStax's permission.

Want to cite, share, or modify this book? This book uses the Creative Commons Attribution License and you must attribute OpenStax.

Attribution information
  • If you are redistributing all or part of this book in a print format, then you must include on every physical page the following attribution:
    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction
  • If you are redistributing all or part of this book in a digital format, then you must include on every digital page view the following attribution:
    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction
Citation information

© Jul 30, 2024 OpenStax. Textbook content produced by OpenStax is licensed under a Creative Commons Attribution License . The OpenStax name, OpenStax logo, OpenStax book covers, OpenStax CNX name, and OpenStax CNX logo are not subject to the Creative Commons license and may not be reproduced without the prior and express written consent of Rice University.

This book utilizes the OpenStax Python Code Runner. The code runner is developed by Wiley and is All Rights Reserved.