2D Dictionary in Python

2D Dictionary in Python

  1. Create 2D Dictionary in Python Method # 1
  2. Create 2D Dictionary in Python Method # 2

In this tutorial, we will discuss how to create a two-dimensional dictionary in Python. A two-dimensional dictionary is a dictionary that contains a dictionary in each index.

We can create a two-dimensional dictionary by either adding a complete dictionary within a dictionary or adding values one by one. Both methods to create a two-dimensional dictionary in Python are explained below.

Create 2D Dictionary in Python Method # 1

In Python, we can add dictionaries within a dictionary to create a two-dimensional dictionary. We can also print the two-dimensional dictionary using the json.dumps() method, which turns the input into a JSON string. The following code example demonstrates how we can create a two-dimensional dictionary in Python.

import json
twoD_dict = dict()
twoD_dict['first_dict'] = {"key1": "val1", "key2": "val2"}
print(json.dumps(twoD_dict, sort_keys=True, indent=2))

Output:

{
  "first_dict": {
    "key1": "val1",
    "key2": "val2"
  }
}

Create 2D Dictionary in Python Method # 2

We can also just create a dictionary within a dictionary and add the key-value pair later. We can create a dictionary using this method in Python in the following way.

import json
twoD_dict = dict()
twoD_dict['first_dict'] = dict()
twoD_dict['first_dict']['key1'] = 'value1'
twoD_dict['first_dict']['key2'] = 'value2'
print(json.dumps(twoD_dict, sort_keys=True, indent=2))

Output:

{
  "first_dict": {
    "key1": "value1",
    "key2": "value2"
  }
}

Related Article - Python Dictionary

  • Check if a Key Exists in a Dictionary in Python
  • Convert a Dictionary to a List in Python
  • Get All the Files of a Directory
  • Find Maximum Value in Python Dictionary
  • Delete a File and Directory in Python
  • Sort a Python Dictionary by Value