Create Multidimensional dictionary – Python


Introduction

Dictionaries in Python are a robust data structure that allows us to store and retrieve data using key-value pairs.

While dictionaries typically store one-dimensional data, it is also possible to create multidimensional dictionaries in Python. 

A multidimensional dictionary is simply a dictionary with more than one dimension, meaning it contains nested dictionaries or other complex data structures.

This article will teach how to create multidimensional dictionaries in Python. We will discuss the following topics:

  • Nested Dictionaries
  • defaultdict
  • dict.fromkeys
  • pandas DataFrame

By the end of this article, you will have a good idea about the various ways to create multidimensional dictionaries in Python. Let’s discuss them one by one.

Nested Dictionaries

One of the easiest ways to create a multidimensional dictionary in Python is by using nested dictionaries.

In this approach, we create a dictionary where each value is another dictionary. Each sub-dictionary can have its key-value pairs, which results in a multidimensional structure.

Here is an example of creating a multidimensional dictionary using a nested dictionary:

Example 1: 2-dimensional dictionary – Python

Below is the Python code example of a 2-dimensional dictionary that stores information about people –

people = {
    "name": "Henry",
    "age": 21,
    "address": {
        "street": "446 Lombard Street",
        "city": "Seattle",
        "state": "Washington"
    }
}

print(people["address"]["street"])
print(people["address"]["city"])

The Output will be –

446 Lombard Street
Seattle

Explanation:

In the above code, the people dictionary has three key-value pairs. The address key contains another dictionary that has the streetcity, and state keys.

We can use the square bracket notations to access a value in a nested dictionary.

Example 2: 3-dimensional dictionary – Python

Below is the Python code example of a 3-dimensional dictionary that stores information about movies –

# creating a 3-dimensional dictionary
movies = {
    'action': {
        'Die Hard': {'year': 1988, 'director': 'John McTiernan'},
        'The Matrix': {'year': 1999, 'director': 'The Wachowskis'}
    },
    'drama': {
        'The Shawshank Redemption': {'year': 1994, 'director': 'Frank Darabont'},
        'Forrest Gump': {'year': 1994, 'director': 'Robert Zemeckis'}
    }
}

# accessing a value in the dictionary
print(movies['action']['Die Hard']['year'])
print(movies['drama']['Forrest Gump']['director'])

The Output will be –

1988
Robert Zemeckis

Explanation:

In this example, we have a movies dictionary with two keys corresponding to film genres: action and drama.

Each of these keys is associated with a second dictionary containing the movie titles as keys and their associated values as a third nested dictionary containing the film’s release year and director.

To access the value of a specific year for a movie, we can use the keys for the genretitle, and year attribute, as shown in the following example: movies['action']['Die Hard']['year'] returns the value 1988, which is the year that Die Hard was released.

We can add further keys and values to this dictionary to store additional movie-related information.

Example 3: 4-dimensional dictionary – Python

Below is the Python code example of a 4-dimensional dictionary that stores information about a school’s classes –

# creating a 4-dimensional dictionary
classes = {
    '2023': {
        'A': {
            'Math': {'teacher': 'Ms. Jones', 'students': ['Alice', 'Bob', 'Charlie']},
            'Science': {'teacher': 'Mr. Smith', 'students': ['Charlie', 'David', 'Emma']}
        },
        'B': {
            'Math': {'teacher': 'Ms. Lee', 'students': ['Frank', 'Gina', 'Helen']},
            'Science': {'teacher': 'Mr. Chen', 'students': ['Ivan', 'John', 'Karen']}
        }
    },
    '2024': {
        'A': {
            'Math': {'teacher': 'Ms. Brown', 'students': ['Linda', 'Mary', 'Nancy']},
            'Science': {'teacher': 'Mr. Wilson', 'students': ['Oscar', 'Peter', 'Queen']}
        },
        'B': {
            'Math': {'teacher': 'Ms. Davis', 'students': ['Robert', 'Sam', 'Tom']},
            'Science': {'teacher': 'Mr. Kim', 'students': ['Uma', 'Vicky', 'Will']}
        }
    }
}

# accessing a value in the dictionary
print(classes['2023']['A']['Math']['students'][0])
print(classes['2024']['B']['Science']['teacher'])

The Output will be –

Alice
Mr. Kim

Explanation:

In this example, we have our first dictionary named classes with two keys corresponding to the year of the classes: ‘2023‘ and ‘2024‘.

Each of these keys is associated with a second dictionary that contains the class sections (‘A‘ and ‘B‘) as keys and their associated values as a third nested dictionary, which contains the class subjects as keys and their associated values as a fourth nested dictionary, which contains the teacher’s name and a list of students.

To access the value of a particular student in a particular class, we can use the keys for the yearsectionsubject, and the index of the student in the list, like this: classes['2023']['A']['Math']['students'][0] would give us the value Alice

, who is the first student in the list for the Math class in section A in the year 2023.

We can add more keys and values to this dictionary to store additional information about the classes.

Example 4: Multidimensional dictionary using Loop – Python

Below is the Python code example to create a 2-dimensional dictionary that stores information about a company’s employees using a loop to populate the dictionary –

# creating a 2-dimensional dictionary using a loop without input from user
employees = {}
departments = ['Sales', 'Engineering']

for department in departments:
    num_employees = int(input(f"Enter number of employees in {department}: "))
    employees[department] = {}
    for i in range(num_employees):
        name = input(f"Enter name of employee {i+1} in {department}: ")
        title = input(f"Enter title of employee {name}: ")
        salary = float(input(f"Enter salary of employee {name}: "))
        employees[department][name] = {'title': title, 'salary': salary}

# accessing a value in the dictionary
print(employees['Sales']['Alice']['salary'])
print(employees['Engineering']['Robin']['title'])

print(employees)

On providing the following data as Input

Enter number of employees in Sales: 1
Enter name of employee 1 in Sales: Alice
Enter title of employee Alice: HOD
Enter salary of employee Alice: 130000
Enter number of employees in Engineering: 2
Enter name of employee 1 in Engineering: Robin
Enter title of employee Robin: Senior Engineer
Enter salary of employee Robin: 180000
Enter name of employee 2 in Engineering: John
Enter title of employee John: Junior Engineer
Enter salary of employee John: 120000

We get the following Output

130000.0
Senior Engineer
{‘Sales’: {‘Alice’: {‘title’: ‘HOD’, ‘salary’: 130000.0}}, ‘Engineering’: {‘Robin’: {‘title’: ‘Senior Engineer’, ‘salary’: 180000.0}, ‘John’: {‘title’: ‘Junior Engineer’, ‘salary’: 120000.0}}}

Explanation:

In this example, we create a 2-dimensional dictionary that stores information about employees in different departments using a loop.

  • We first create an empty dictionary named employees,
  • then prompt the user to enter the number of employees in each department.
  • We use a nested loop to create a dictionary of employee information for each employee and then add that dictionary to the employees dictionary using the employee’s name as the key.

To access the value of a particular employee’s salary, we can use the keys for the departmentemployee’s name, and salary, like this: employees['Sales']['Alice']['salary'] would give us the value 130000.0

, which is Alice’s salary in the Sales department.

We can modify this code to add more loops and dimensions to the dictionary to store additional information about the employees.

defaultdict

The defaultdict class is a subclass of the built-in dict class in Python. It lets us set a default value for any key that doesn’t exist in the dictionary.

This feature is beneficial when creating multidimensional dictionaries since we can set a default value of another dictionary.

NOTE: To use defaultdict class, first, we need to import it from collections module in our Python file.

Here is an example of creating a multidimensional dictionary using defaultdict:

Example

Below is the Python code –

# Import the module
from collections import defaultdict

people = defaultdict(dict)
people["name"] = "Henry"
people["age"] = 21
people["address"]["street"] = "446 Lombard Street"
people["address"]["city"] = "Seattle"
people["address"]["state"] = "Washington"

print(people["address"]["state"])
print(people["address"]["street"])

The Output will be –

Washington
446 Lombard Street

Explanation:

In this example,

  • First, we import defaultdict class form collections module.
  • Then we create a people dictionary as a defaultdict and set the default value to a new empty dictionary.
  • Then, we set the name and age keys with string and integer values, respectively. 
  • Finally, we set the address key to another dictionary, which can be accessed using the square bracket notation.

We can use the square bracket notation to access a value in a defaultdict, just like we would do with a regular dictionary.

dict.fromkeys

The dict.fromkeys() method is a handy function in Python.

dict.fromkeys() method creates a new dictionary with keys derived from a given sequence and sets all values to default. This method can create a multidimensional dictionary by specifying the default value as another dictionary.

Here is an example of creating a multidimensional dictionary using dict.fromkeys() method:

Example

Below is the Python code –

all_keys = ["name", "age", "address"]
people = dict.fromkeys(all_keys, {})
people["name"] = "Henry"
people["age"] = 21
people["address"]["street"] = "446 Lombard Street"
people["address"]["city"] = "Seattle"
people["address"]["state"] = "Washington"

print(people["address"]["street"])
print(people["address"]["state"])

The Output will be –

446 Lombard Street
Washington

Explanation:

In this example, 

  • We have an all_keys list containing the keys for the new dictionary.
  • Then with these keys, we use the dict.fromkeys() method to create a new dictionary and set the default value to a new empty dictionary.
  • Then, we set the name and age keys with string and integer values, respectively.
  • Finally, we set the address key to another dictionary, which can be accessed using the square bracket notation.

pandas DataFrame

Pandas is a well-known data analysis library in Python. One of its essential data structures is the DataFrame, a two-dimensional table-like structure.

We can use the DataFrame to create multidimensional dictionaries in Python.

Note: Use the pip function to install the Pandas module, then import it into your Python code.

Here is an example of creating a multidimensional dictionary using a pandas DataFrame:

Example

Below is the Python code –

import pandas as pd

person = pd.DataFrame({
    "name": ["Henry"],
    "age": [21],
    "address": [{
        "street": "446 Lombard Street",
        "city": "Seattle",
        "state": "Washington"
    }]
})

print(people.loc[0, "address"]["city"])
print(people.loc[0, "address"]["street"])

The Output will be –

Seattle
446 Lombard Street

Explanation:

In this example, 

  • First, we create a dictionary ‘person’ using a pandas DataFrame.
  • Then we map each column in the DataFrame to a key in the dictionary.
  • Additionally, the address column contains a list of dictionaries representing the nested dictionary structure.

Conclusion

This blog has covered various ways to create multidimensional dictionaries in Python. Each method has advantages and disadvantages, so you should select the one that best suits your needs.

I hope you found this article helpful.

Create Multidimensional dictionary – Python

You may like to Explore –

keys() Method – Python Dictionary | Explained with Examples

items() method – Python Dictionary Class

get() Method – Python Dictionary

Cheers!

Happy Coding.

About the Author

This article was authored by Satyam Tripathi. Verified by Rawnak.