Python - How To 2D Dictionary in Python

ID : 179

viewed : 195

Tags : PythonPython Dictionary

vote vote

100

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 HOW TO?