List of Dictionaries in Python

Python List of dictionaries

We use both lists and dictionaries in our python programs. Lists are used to store atomic objects while dictionaries store key-value pairs. In this article, we will discuss how we can create a list of dictionaries in python. We will also discuss ways to search records in a list of dictionaries and also to sort them.

How to Create a List of Dictionaries in Python?

A list of dictionaries in python is a list having dictionaries as all of its elements. To create a list of dictionaries, we simply have to create an empty list and add dictionaries to it as the elements. Let us understand this using the following example.

Suppose that we have a list of names of laptops as follows.

Now we have to store the amount of RAM in each of the laptops with their name. For this, we cannot use a simple list. We will create a list of dictionaries to store the name and RAM of the laptops as discussed below.

For each laptop, we will create a dictionary with “name” and “RAM” as its keys with their associated values. After creating the dictionaries, we will create an empty list. Then, we will insert all the dictionaries into the list using the append() method as follows.

Output:

After all the append operations, we will get a list of dictionaries in the variable laptops. You can also observe this in the output.

Instead of using the append() method, you can also initialize the list with the created dictionaries to create a list of dictionaries. I would suggest you use this approach as this is more efficient in terms of code length as well as execution.

Output:

In the above example, the output is similar to the previous code. However, the above code has a much faster execution than the previous one.

How to Access Elements of a List of Dictionaries?

To access the elements from a list of dictionaries, we will first access each dictionary in the list using a for loop. After that, we will access each key-value pair in the dictionary using another for loop as shown below.

Output:

Search in a List of Dictionaries in Python

To search for an element in the list of dictionaries, we can use the for loop. While traversing the list of dictionaries, we can check for the key-value pairs for the desired value using the equality operator. Once we find the desired value, we can print all the associated information.

For instance, suppose that we have to search the name of the laptop that has the RAM value of 16. For this, we will traverse through each dictionary in the list of dictionaries and check if the value of RAM in the dictionary is 16. Once we find a dictionary with the RAM value 16, we will print the name of the laptop using the print() function as follows.

Output:

Update Values in a List of Dictionaries in Python

To update the values in a list of dictionaries in python, we will first search the dictionary to be updated using the approach discussed above. After that, we will update the value for the given key. For instance, we can update the RAM of laptop1 to 32 as follows.

Output:

In the output, we have printed the RAM of laptop1 before and after updating it. In the code, you can observe that we have to perform the search operation to select the dictionary to update. After finding the dictionary to be updated, we just update the desired key.

How to Sort List of Dictionaries in Python?

To sort a list of dictionaries in python, we will have to specify the key according to which the dictionaries will be sorted. We will choose a specific key-value pair from the dictionaries that will be used as the key for sorting the list of dictionaries. Here, we have to keep in mind that the key of the key-value pair that is to be used for comparing the dictionaries must be present in all the dictionaries in the list. 

For instance, if we have to sort the dictionaries of laptops according to their RAM value, we will first create a function getVal() that takes a dictionary as input and returns the value associated with the key “RAM” of the dictionary. After that, we will pass the getVal() function to the sort() method as an input argument for the parameter key. The sort() method when invoked on the list of dictionaries with the getVal() function as an input argument for the parameter “key”, will sort the list as follows.

Output:

Alternatively, you can use the sorted() function to get a new sorted list of dictionaries if you don’t want to change the existing list.

Instead of the getVal() function, we can also use the lambda functions to sort the list of dictionaries. Again, we will create a lambda function that takes a dictionary as input and returns the value associated with the key “RAM” of the dictionary. Then, we will pass this lambda function as an input argument to the “key” parameter of the sort() method to sort the list of dictionaries.

Output:

You can also use the sorted() function with the lambda function to sort the list of dictionaries if you don’t want to change the existing list.

Conclusion

In this article, we have discussed the list of dictionaries in python. We also saw how to create, update, search elements from, and sort a list of dictionaries using different approaches. 

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!


import_contacts

You may also like:

Related Posts

  • Python sort list of lists
    17 November

    Sort List of Lists in Python

    Table of ContentsSort List of Lists Using the sort() Method in PythonUsing the itemgetter() methodUsing Lambda FunctionsSort List of Lists Using the sorted() Function in PythonSort lists of lists on the basis of the length of the inner listsConclusion Several times we use 2-D lists or lists of lists in our programs to represent a […]

  • Remove nan from list in Python
    16 November

    Remove nan From List In Python?

    Table of ContentsWhat is nan in python?How to remove nan from list in python?Remove nan from list using the str() functionRemove nan from list using math.isnan() functionRemove nan from list using numPy.isnan() functionRemove nan from list using pandas.isnull() functionConclusion In python, nan is a special value used to represent missing values. In this article, we […]

  • List intersection in Python
    11 November

    List intersection in python

    Table of ContentsWhat is the list intersection in Python?Ways to find the list intersection in PythonUsing the for loop to achieve list intersection in PythonUsing the set() function to find list intersection in PythonUsing the intersection() function to find list intersection in PythonUsing the filter() and lambda functions to find list intersection in PythonUsing the […]

  • Initialize list with zeros in Python
    25 October

    Four Ways To Initialize List With Zeros In Python

    Table of ContentsWhy Initialize List with Zeros in Python?How Can We Initialize List With Zeros In Python?Initialize List With Zeros Using * Operator In PythonInitialize List With Zeros Using  itertools.repeat() FunctionInitialize List With Zeros Using  Generator Comprehension In PythonInitialize List With Zeros Using  List Comprehension In PythonConclusion Lists in Python are one of the most […]

  • 06 October

    How to find index of all occurrences in list in Python

    Table of ContentsThe easiest method – Using list count() methodThe Basic Method – Using for loopsThe shortest method – Using the enumerate() functionThe fastest method – Using a numpy arrayUsing itertools moduleUsing more-itertools LibraryUsing index() function List is a data type in Python. It is used to store multiple values in one variable. If you […]

  • Convert list to matrix in Python
    21 August

    Convert list to matrix in Python

    Table of ContentsUsing the while loop to convert list to matrix in Python.Use the numpy.array() method to convert list to matrix in Python.Using the numpy.asarray() method to convert list to matrix in Python. Python provides some in-built data types to stock multiple items in a single variable. A List is one among these built-in data […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.