Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The values in a list of dictionaries can be retrieved by iterating through each dictionary in the list and accessing the value for the specified key. For example, if we have a list of dictionaries containing "name" and "age" keys, we can retrieve all the "age" values by using a loop and the dictionary[key] syntax like this:

list_of_dicts = [{"name":"John", "age":25}, {"name":"Anna", "age":30}, {"name":"Mark", "age":27}]

# Retrieve all the age values
ages = []
for d in list_of_dicts:
    ages.append(d["age"])

# Print the ages
print(ages) # Output: [25, 30, 27]

Alternatively, we can also use list comprehension to retrieve specific values from the dictionaries like this:

list_of_dicts = [{"name":"John", "age":25}, {"name":"Anna", "age":30}, {"name":"Mark", "age":27}]

# Retrieve all the age values using list comprehension
ages = [d["age"] for d in list_of_dicts]

# Print the ages
print(ages) # Output: [25, 30, 27]