How To Create A List Of Dictionary In Python

In this tutorial, we will discuss how to create a list of dictionaries in Python. A list is a versatile, ordered, and mutable data structure that can store multiple values, while a dictionary stores key-value pairs, which are convenient for organizing and accessing data.

When you combine these two structures, you get a list of dictionaries. This comes in handy when you need to store more complex datasets where each element in the list consists of multiple attributes.

So let’s dive in and learn how to create and manipulate a list of dictionaries in Python.

Step 1: Create an Empty List

The first step is to create an empty list, which will later be filled with dictionaries. You can do this by assigning an empty set of square brackets [] to a variable:

Step 2: Append Dictionaries to the List

Once you have an empty list, you can add dictionaries to it using the append() method. Start by defining a new dictionary with key-value pairs:

Then, append this dictionary to the list:

You can repeat this process to add additional dictionaries to the list:

Now, if you print the list, you will see it contains the three dictionaries:

[{'name': 'John', 'age': 28}, {'name': 'Alice', 'age': 23}, {'name': 'Bob', 'age': 35}]

Alternative: List Comprehension

Another way to create a list of dictionaries is by using list comprehension. This method allows you to generate the entire list with a single line of code.

Here’s an example that creates a list of dictionaries where each dictionary contains keys ‘even’ and ‘odd’, representing the even and odd numbers from a given range:

Print the list to see the output:

[{'even': 0, 'odd': 1}, {'even': 2, 'odd': 3}, {'even': 4, 'odd': 5}, {'even': 6, 'odd': 7}, {'even': 8, 'odd': 9}]

Step 3: Access Data within the List of Dictionaries

To access individual dictionaries or values within the list, you can use indexing and key-value pairs. Here’s how to access the dictionary or the ‘name’ value for the second element in the list:

Printing these values, you’ll see:

{'name': 'Alice', 'age': 23}
Alice

Full code

Conclusion

In this tutorial, we’ve learned how to create a list of dictionaries in Python, both by appending dictionaries to an existing list and using list comprehension. We’ve also looked at how to access data within the list. With a list of dictionaries, you can store complex datasets and easily access the information you need.