A Guide to Nested Dictionaries in Python with Loop Examples

A Guide to Nested Dictionaries in Python with Loop Examples

Yes, dictionaries can indeed be nested in Python. Nesting dictionaries means having a dictionary where the values are themselves dictionaries. Here are five examples of nested dictionaries along with examples of how you might use loops with them:

  1. Nested Dictionary Example 1:
students = {
    'Alice': {'age': 20, 'major': 'Computer Science'},
    'Bob': {'age': 22, 'major': 'Engineering'}

# Loop to print student names and their majors
for name, info in students.items():
    print(f"{name}: {info['major']}")
  1. Nested Dictionary Example 2:
countries = {
    'USA': {'capital': 'Washington D.C.', 'population': 331},
    'China': {'capital': 'Beijing', 'population': 1441}

# Loop to print country names and their populations
for country, info in countries.items():
    print(f"{country}: {info['population']} million")
  1. Nested Dictionary Example 3:
employees = {
    'John': {'department': 'HR', 'salary': 50000},
    'Emily': {'department': 'Finance', 'salary': 60000}

# Loop to calculate total salary expense
total_salary = 0
for info in employees.values():
    total_salary += info['salary']
print(f"Total salary expense: ${total_salary}")
  1. Nested Dictionary Example 4:
inventory = {
    'apple': {'quantity': 100, 'price': 0.5},
    'banana': {'quantity': 150, 'price': 0.3}

# Loop to calculate total inventory value
total_value = 0
for item, details in inventory.items():
    total_value += details['quantity'] * details['price']
print(f"Total inventory value: ${total_value}")
  1. Nested Dictionary Example 5:
books = {
    'Python Programming': {'author': 'Guido van Rossum', 'pages': 400},
    'Machine Learning': {'author': 'Andrew Ng', 'pages': 500}

# Loop to print book titles and their authors
for title, info in books.items():
    print(f"{title} by {info['author']}")

In these examples, dictionaries are nested within each other, and loops are used to iterate over the keys and values of the outer and inner dictionaries for various purposes such as printing information, calculating totals, etc.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!