How to Convert a 2D Array to a Dictionary in Python?

Estimated read time 1 min read

To convert a 2D array (or a nested list) to a dictionary in Python, you can use a dictionary comprehension. The inner lists of the 2D array can be used to define key-value pairs in the resulting dictionary. Here’s an example:

array = [['key1', 'value1'], ['key2', 'value2'], ['key3', 'value3']]

dictionary = {sublist[0]: sublist[1] for sublist in array}


In the code above, we have a 2D array called array, where each inner list represents a key-value pair. We use a dictionary comprehension to iterate over each sublist in the array. The first element of each sublist is used as the key, and the second element is used as the value in the resulting dictionary.

The output will be a dictionary {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}, where the keys and values are derived from the corresponding elements in the 2D array.

Note that if the inner lists in the 2D array do not contain exactly two elements (a key and a value), an error will occur. Ensure that the structure of the 2D array matches the expected key-value pairs for successful conversion to a dictionary.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply