How to create list of dictionary in Python

How to create list of dictionary in Python

Creating a list of dictionaries in Python is straightforward. A dictionary is defined using curly braces {} with key-value pairs, and a list is defined using square brackets []. You can combine them to create a list containing multiple dictionaries.

Here are a few methods to create a list of dictionaries:

1. Direct Initialization:

You can directly initialize a list containing multiple dictionaries.

list_of_dicts = [ {"name": "John", "age": 25, "city": "New York"}, {"name": "Marie", "age": 22, "city": "Boston"}, {"name": "Mike", "age": 30, "city": "Chicago"} ] print(list_of_dicts) 

2. Using a Loop:

You can use a loop to create a list of dictionaries, especially when there's a pattern or when data is coming from an external source.

names = ["John", "Marie", "Mike"] ages = [25, 22, 30] cities = ["New York", "Boston", "Chicago"] list_of_dicts = [] for name, age, city in zip(names, ages, cities): list_of_dicts.append({"name": name, "age": age, "city": city}) print(list_of_dicts) 

3. Using List Comprehension:

Python's list comprehension provides a concise way to create lists.

names = ["John", "Marie", "Mike"] ages = [25, 22, 30] cities = ["New York", "Boston", "Chicago"] list_of_dicts = [{"name": name, "age": age, "city": city} for name, age, city in zip(names, ages, cities)] print(list_of_dicts) 

All of the methods above will give you the same output:

[{'name': 'John', 'age': 25, 'city': 'New York'}, {'name': 'Marie', 'age': 22, 'city': 'Boston'}, {'name': 'Mike', 'age': 30, 'city': 'Chicago'}] 

Choose the method that best fits the specific structure and needs of your data.


More Tags

android-virtual-device use-effect httpserver android-camera-intent viewmodel plsql qt bit ip any

More Programming Guides

Other Guides

More Programming Examples