Array or List of Dictionaries in Python

Hemank Mehtani Dec 21, 2022 Sep 26, 2021
Array or List of Dictionaries in Python

A dictionary in Python constitutes a group of elements in the form of key-value pairs. A list can store elements of different types under a common name and at specific indexes.

In Python, we can have a list or an array of dictionaries. In such an object, every element of a list is a dictionary. Every dictionary can be accessed using its index.

See the following code.

lst = [{'a':0,'b':1,'c':2},
       {'d':3,'c':4,'b':5},
       {'a':5,'d':6,'e':1}]

print(lst[1])
print(lst[1]['c'])

Output:

{'d': 3, 'c': 4, 'b': 5}
4

In the above example, we create such a list. Also, we access a dictionary individually using its index and extract the value of a specific key. Remember, every dictionary is a separate element in the list. No two dictionaries are related so that we can have similar keys or values in each dictionary.

We can append a dictionary to this list using the append() function.

For example,

lst = [{'a':0,'b':1,'c':2},
       {'d':3,'c':4,'b':5},
       {'a':5,'d':6,'e':1}]

lst.append({'f':4,'g':5,'c':2})

print(lst)

Output:

[{'a': 0, 'b': 1, 'c': 2}, {'d': 3, 'c': 4, 'b': 5}, {'a': 5, 'd': 6, 'e': 1}, {'f': 4, 'g': 5, 'c': 2}]

This method of creating an array or a list of dictionaries can be tedious at times.

List comprehension can create a list of empty dictionaries or repeat the same dictionary as an element of a list for a required number of times.

See the following example.

lst1 = [dict() for i in range(4)]
lst2 = [{'a':1,'b':2} for i in range(4)]

print(lst1)
print(lst2)

Output:

[{}, {}, {}, {}]
[{'a': 1, 'b': 2}, {'a': 1, 'b': 2}, {'a': 1, 'b': 2}, {'a': 1, 'b': 2}]

In the above example, we create a list of empty dictionaries and have a dictionary repeated as a list element. The dict() function creates empty dictionaries. We can append values in these empty dictionaries accordingly.

Related Article - Python Dictionary

Related Article - Python List