Skip to main content

How to convert a dictionary to a dictionary of dictionaries in Python

How to convert a dictionary to a dictionary of dictionaries in Python.

Here's a detailed step-by-step tutorial on how to convert a dictionary to a dictionary of dictionaries in Python.

Step 1: Understand the Problem

Before we jump into the solution, let's make sure we understand the problem. We have an existing dictionary, and we want to convert it into a dictionary of dictionaries. In other words, we want to transform the keys of the original dictionary into nested dictionaries.

Step 2: Example Dictionary

Let's start by defining an example dictionary that we can use throughout the tutorial. For this example, let's consider a dictionary representing student grades:

grades = {
'Alice': 85,
'Bob': 92,
'Charlie': 78
}

Step 3: Create a Dictionary of Dictionaries

To convert the dictionary into a dictionary of dictionaries, we'll follow these steps:

  1. Create an empty dictionary to store the result.
  2. Iterate over the keys and values of the original dictionary.
  3. For each key-value pair, create a new inner dictionary with the original key as the only key and the original value as its value.
  4. Assign the inner dictionary to the original key in the result dictionary.

Here's the Python code that implements these steps:

result = {}

for key, value in grades.items():
result[key] = {key: value}

The items() method is used to iterate over the keys and values of the original dictionary. For each key-value pair, we create a new inner dictionary and assign it to the original key in the result dictionary.

Step 4: Print the Result

Finally, let's print the resulting dictionary of dictionaries to verify that the conversion was successful. We can use a simple loop to iterate over the keys and values of the result dictionary.

for key, value in result.items():
print(key, value)

This will output:

Alice {'Alice': 85}
Bob {'Bob': 92}
Charlie {'Charlie': 78}

Step 5: Conclusion

Congratulations! You have successfully converted a dictionary into a dictionary of dictionaries in Python. You can now apply this technique to your own dictionaries and modify the code as needed.

I hope this tutorial was helpful! Let me know if you have any further questions.