How to Create a List of Dictionaries in Python?

Estimated read time 2 min read

To create a list of dictionaries in Python, you can define each dictionary as a separate element in the list. Here’s an example code that creates a list of dictionaries, where each dictionary contains information about a person:

person1 = {"name": "John", "age": 30, "city": "New York"}
person2 = {"name": "Alice", "age": 25, "city": "San Francisco"}
person3 = {"name": "Bob", "age": 40, "city": "Chicago"}

people = [person1, person2, person3]

# print the list of dictionaries
print(people)

In this example, we define three dictionaries person1, person2, and person3, where each dictionary contains information about a person’s name, age, and city. Then we create a list people that contains these dictionaries as separate elements. Finally, we print the list of dictionaries using the print() function.

You can also create a list of dictionaries using a loop and user input. Here’s an example:

people = []

# prompt the user to enter information about each person
while True:
    name = input("Enter person's name (or 'done' to exit): ")
    if name == "done":
        break
    age = int(input("Enter person's age: "))
    city = input("Enter person's city: ")

    # create a dictionary for this person
    person = {"name": name, "age": age, "city": city}

    # add the dictionary to the list
    people.append(person)

# print the list of dictionaries
print(people)

In this example, we use a while loop to prompt the user to enter information about each person. We use the input() function to get the person’s name and city, and the int() function to convert the age input to an integer. Then we create a dictionary person that contains the person’s information, and add it to the people list using the append() method. Finally, we print the list of dictionaries using the print() function.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply