In this tutorial, we will learn how to get a key and its value from a list of dictionaries in Python. This is very helpful when you are dealing with data stored in dictionaries and want to perform operations on specific keys and their values. We will walk through a step-by-step process to achieve this task with ease.
Step 1: Create a list of dictionaries
First, you need to create a list containing multiple dictionaries. Each dictionary in the list should have a pair of keys and values. Here, we create a list called my_list
which contains three dictionaries.
1 2 3 4 5 |
my_list = [ {"name": "John", "age": 28}, {"name": "Alice", "age": 24}, {"name": "Bob", "age": 22} ] |
Step 2: Use a loop to iterate over the list of dictionaries
Next, you need to iterate through the list of dictionaries using a loop. For this, we will use the for
loop in Python. This will allow us to access each dictionary in the list one by one.
1 2 |
for dictionary in my_list: # Your code to get the key and value will go here |
Step 3: Use the items()
method to get key-value pairs from the dictionary
To get the key and value from a dictionary, you can use the items()
method. This method returns a view object displaying a list of the dictionary’s key-value pairs.
Inside the for loop, you will call this method on the dictionary
variable to get its key-value pairs.
1 2 3 |
for dictionary in my_list: for key, value in dictionary.items(): # Your code to perform operations on key and value will go here |
In the example above, the inner for
loop iterates over the key-value pairs returned by the items()
method.
Step 4: Perform operations on the key and value
Now that you have access to the key and value inside the inner for
loop, you can perform any operation you want. In this tutorial, we will simply print the key and its corresponding value.
1 2 3 |
for dictionary in my_list: for key, value in dictionary.items(): print(f"{key}: {value}") |
This code will display the keys and their values for each dictionary in the list.
Full Code
1 2 3 4 5 6 7 8 9 |
my_list = [ {"name": "John", "age": 28}, {"name": "Alice", "age": 24}, {"name": "Bob", "age": 22} ] for dictionary in my_list: for key, value in dictionary.items(): print(f"{key}: {value}") |
Output
name: John age: 28 name: Alice age: 24 name: Bob age: 22
Conclusion
In this tutorial, you have learned how to get the key and value from a list of dictionaries in Python. You can follow these steps to work with more complex data structures and apply a variety of operations to the keys and values according to your needs.
The Python documentation provides extensive information on dictionaries and their methods, which can be useful for further exploring this topic.