Python List of Dictionaries
List of Dictionaries in Python
In Python, you can have a List of Dictionaries. You already know that elements of the Python List could be objects of any type.
In this tutorial, we will learn how to create a list of dictionaries, how to access them, how to append a dictionary to list and how to modify them.
Create a List of Dictionaries in Python
In the following program, we create a list of length 3, where all the three elements are of type dict.
Python Program
myList = [
{
'foo':12,
'bar':14
},
{
'moo':52,
'car':641
},
{
'doo':6,
'tar':84
}
]
print(myList)
Output
[{'foo': 12, 'bar': 14}, {'moo': 52, 'car': 641}, {'doo': 6, 'tar': 84}]
Each element of the list is a dictionary.
Access key:value pairs in List of Dictionaries
Dictionary is like any element in a list. Therefore, you can access each dictionary of the list using index.
And we know how to access a specific key:value of the dictionary using key.
In the following program, we shall print some of the values of dictionaries in list using keys.
Python Program
myList = [
{
'foo':12,
'bar':14
},
{
'moo':52,
'car':641
},
{
'doo':6,
'tar':84
}
]
print(myList[0])
print(myList[0]['bar'])
print(myList[1])
print(myList[1]['moo'])
print(myList[2])
print(myList[2]['doo'])
Output
{'foo': 12, 'bar': 14}
14
{'moo': 52, 'car': 641}
52
{'doo': 6, 'tar': 84}
6
Update key:value pairs of a Dictionary in List of Dictionaries
In the following program, we shall update some of the key:value pairs of dictionaries in list: Update value for a key in the first dictionary, add a key:value pair to the second dictionary, delete a key:value pair from the third dictionary.
Python Program
myList = [
{
'foo':12,
'bar':14
},
{
'moo':52,
'car':641
},
{
'doo':6,
'tar':84
}
]
#update value for 'bar' in first dictionary
myList[0]['bar'] = 52
#add a new key:value pair to second dictionary
myList[1]['gar'] = 38
#delete a key:value pair from third dictionary
del myList[2]['doo']
print(myList)
Output
[{'foo': 12, 'bar': 52}, {'moo': 52, 'car': 641, 'gar': 38}, {'tar': 84}]
Append a Dictionary to List of Dictionaries
In the following program, we shall append a dictionary to the list of dictionaries.
Python Program
myList = [
{
'foo':12,
'bar':14
},
{
'moo':52,
'car':641
},
{
'doo':6,
'tar':84
}
]
#append dictionary to list
myList.append({'joo':48, 'par':28})
print(myList)
Output
[{'foo': 12, 'bar': 14}, {'moo': 52, 'car': 641}, {'doo': 6, 'tar': 84}, {'joo': 48, 'par': 28}]
Summary
In this tutorial of Python Examples, we learned about list of dictionaries in Python and different operations on the elements of it, with the help of well detailed examples.