In this tutorial, you will learn how to convert a list of dictionaries to a dictionary in Python. This can be useful in various scenarios such as consolidating data from multiple sources or converting JSON data to a more usable format.
Step 1: Define the function
First, let’s define a function that takes a list of dictionaries as its input and outputs a single dictionary.
1 2 3 4 5 |
def merge_dicts(dict_list): result = {} for d in dict_list: result.update(d) return result |
This function performs the task by iterating through each dictionary in the input list and updating the result dictionary with the key-value pairs of the current dictionary.
Step 2: Use the function
Now, let’s create an example list of dictionaries and use the function we just defined to merge these dictionaries.
1 2 3 4 5 6 7 8 |
example_dicts = [ {"name": "Alice", "age": 30}, {"city": "New York", "state": "NY"}, {"country": "USA", "continent": "North America"} ] output_dict = merge_dicts(example_dicts) print(output_dict) |
When you run this code, it will display the following output:
{'name': 'Alice', 'age': 30, 'city': 'New York', 'state': 'NY', 'country': 'USA', 'continent': 'North America'}
Congratulations, you have successfully merged the list of dictionaries into a single dictionary!
Full Code
Here’s the complete code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
def merge_dicts(dict_list): result = {} for d in dict_list: result.update(d) return result example_dicts = [ {"name": "Alice", "age": 30}, {"city": "New York", "state": "NY"}, {"country": "USA", "continent": "North America"} ] output_dict = merge_dicts(example_dicts) print(output_dict) |
And the output:
{'name': 'Alice', 'age': 30, 'city': 'New York', 'state': 'NY', 'country': 'USA', 'continent': 'North America'}
Conclusion
In this tutorial, you learned how to convert a list of dictionaries to a dictionary in Python by defining a function that iterates through each dictionary in the list and updates a result dictionary with the key-value pairs. This method can be useful in various data processing tasks, such as consolidating data from different sources or converting JSON data to a more usable format.