How to Create a Python List of Dictionaries
To create a list of dictionaries in Python, pass them as a comma-separated list inside []
(square brackets) and store the result in a variable.
Let's try this out with an example.
dict1 = {'a':1, 'b':2}
dict2 = {'c':3, 'd':4}
items = [dict1, dict2]
print(items)
[{'a': 1, 'b': 2}, {'c': 3, 'd': 4}]
Add Dictionary to Existing List
To add dictionaries as elements in an existing Python list, use the .append()
function like this:
dict1 = {'a':1, 'b':2}
dict2 = {'c':3, 'd':4}
items = []
items.append(dict1)
items.append(dict2)
print(items)
[{'a': 1, 'b': 2}, {'c': 3, 'd': 4}]
Accessing Dictionary Values within a List
To access the value of a dictionary list item, access the index of the dictionary first, then the dictionary key (both in separated square brackets.)
items = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}]
b = items[0]['b']
print(b)
2
Update Dictionary Values in a List
To update a dictionary value that's in a list, use the same access method as above, then set the value using the =
(equals) operator.
items = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}]
items[0]['b'] = 10
b = items[0]['b']
print(b)
10