Creating a Nested Dictionary using a given List in Python


Python dictionaries are flexible data structures that hold key-value pairs effectively. A nested dictionary is a hierarchical data structure to organize and manage large amounts of data. This article shows how to construct a nested dictionary from a given list, enabling dictionary users to perform a variety of tasks.

Syntax

Nest multiple levels of dictionaries to accommodate complex data structures.

nested_dict = { 'outer_key': { 'inner_key': 'value' } }

Algorithm

1. Create a new dictionary to contain the layered structure.

2. Go through the given list iteratively.

3. Extract the necessary information for keys and values for each item in the list.

4. Verify the nested dictionary to see if the outer key is present.

5. If it exists, see if the inner key for that outer key exists.

6. Otherwise, add it or change the value.

7. If the outer key is missing, construct a new inner dictionary with the specified key-value pair and add it to the nested dictionary.

Example

employee_list = [
   (101, 'John', 30, 'HR'),
   (102, 'Jane', 28, 'Engineering'),
   (103, 'Mike', 32, 'Finance')
]

employee_data = {}

for employee in employee_list:
   employee_id, name, age, department = employee
   if department in employee_data:
      employee_data[department][employee_id] = {'name': name, 'age': age}
   else:
      employee_data[department] = {employee_id: {'name': name, 'age': age}}

Problem statement is: Use employee data to make a nested dictionary. This should group employee data into tuples that represent employee_id, name, age, and department.

Create an empty dictionary called employee data. Information like employee id, name, age, and department employee ID is stored by looping over the employee list. If the department exists as an outside key in employee data, update the employee's information. If it does not, build a new inner dictionary with the key employee id and store the employee's data.

Additional Examples

1. Assume they have a list of students' grades in various disciplines. Arrange this data using a hierarchy data structure based on their grades or performance.

2. There is sales data for numerous items in various geographies. This data is converted to structured form using a layered dictionary depending on product categories and locations.

Certainly! Code examples below that demonstrate ways to generate and operate complex nested dicts.

Nested Dictionary with User Input

nested_dict = {}

num_employees = int(input("Total headcount? :"))

for i in range(num_employees):
   employee_id = int(input(f"Enter Employee {i+1} ID: "))
   name = input(f"Enter Employee {i+1} Name: ")
   age = int(input(f"Employee {i+1} Age: "))
   department = input(f"Employee {i+1} Department: ")

   if department in nested_dict:
      nested_dict[department][employee_id] = {'name': name, 'age': age}
   else:
      nested_dict[department] = {employee_id: {'name': name, 'age': age}}

print("Nested Dictionary:", nested_dict)

Nested Dictionary using defaultdict

from collections import defaultdict

employee_list = [
   (101, 'John', 30, 'HR'),
   (102, 'Jane', 28, 'Engineering'),
   (103, 'Mike', 32, 'Finance'),
   (104, 'Alice', 25, 'Engineering'),
]

employee_data = defaultdict(dict)

for employee in employee_list:
   employee_id, name, age, department = employee
   employee_data[department][employee_id] = {'name': name, 'age': age}

print("Nested Dictionary using defaultdict:", dict(employee_data))

Merge Two Nested Dictionaries

sales_data1 = {
   'ProductA': {'Region1': 100, 'Region2': 200},
   'ProductB': {'Region1': 150, 'Region3': 300},
}

sales_data2 = {
   'ProductA': {'Region2': 250, 'Region4': 180},
   'ProductC': {'Region1': 120, 'Region3': 80},
}

merged_sales_data = {}

for product, region_data in sales_data1.items():
   merged_sales_data[product] = region_data.copy()

for product, region_data in sales_data2.items():
   if product in merged_sales_data:
      merged_sales_data[product].update(region_data)
   else:
      merged_sales_data[product] = region_data

print("Merged Sales Data:", merged_sales_data)

Access Values in a Nested Dictionary

student_grades = {
   'John': {'Math': 90, 'Science': 85, 'History': 78},
   'Jane': {'Math': 95, 'English': 88, 'Science': 92},
}

jane_science_grade = student_grades['Jane']['Science']
print("Jane's Science Grade:", jane_science_grade)

john_history_grade = student_grades.get('John', {}).get('History', 'Not available')
print("John's History Grade:", john_history_grade)

Applications

  • Modeling organizational hierarchies, file systems, or configurations are examples of dealing with hierarchical data structures.

  • Managing complicated data, such as nested JSON objects, graphs, or multi-dimensional datasets.

  • Describe connections between things, such as dependencies or parent-child connections.

  • Algorithms that efficiently traverse, explore, or sort over hierarchical data structures.

Conclusion

This article has illustrated ways to build a nested dictionary in Python using a list. The installation, syntax, and algorithm are discussed in detail. Nested dictionaries are an effective tool for handling and organizing data. Lists make it simple to access and modify certain data structure pieces, which improves the usefulness and efficiency of Python programmes.

Updated on: 09-Aug-2023

354 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements