. Advertisement .
..3..
. Advertisement .
..4..
In Python, a dictionary is a collection of elements that take the form of key-value pairs. A list can store elements of various types under the same name and at different indexes.
This article will discuss about “Array or List of Dictionaries in Python”. Now let’s get started.
What is Dictionaries in Python?
A dictionary in Python is an unordered collection of data values, used to store data values like maps, unlike other data types that only hold unique values. is the element, the dictionary holds the key:value pair. The key:value pair is provided in the dictionary to optimize itself.
Declare the dictionary:
dictionary_name = {key_1: value_1, key_2: value_2, ..., key_n: value_n}
We can also use the built-in function dict() to declare a Dictionary, for example:
friend_ages = dict({"Rolf": 24, "Adam": 30, "Anne": 27})
# or
friend_ages = dict([("Rolf", 24), ("Adam", 30), ("Anne", 27)])
Manipulations with Array or List of Dictionaries in Python
Retrieve value from a list
For example:
lst = [{'aarti':36,'heeya':45},
{'saurabh':56,'sakshi':65}]
print(lst[1])
print(lst[1]['sakshi'])
Output:
{'saurabh': 56, 'sakshi': 65}
65
Retrieve value from a array
For example:
lst1 = [{'aarti':36,'heeya':45} for i in range(4)]
print(lst1)
Output:
[{'aarti': 36, 'heeya': 45}, {'aarti': 36, 'heeya': 45}, {'aarti': 36, 'heeya': 45}, {'aarti': 36, 'heeya': 45}]
Create an empty dictionary with dict()
An empty dictionary can be created by simply enclosing curly braces {}. For eaample:
lst1 = [dict() for i in range(3)]
print(lst1)
Output:
[{}, {}, {}]
Add a dictionary to list by 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}]
Conclusion
Those simple approaches presented above are simple solutions to the “Array or List of Dictionaries in Python“.
Please leave all your concerns in the comments section if you have any further questions. I wish you all an effective day with your tool.
Leave a comment