Categories
Python Answers

How to get a list of values from a list of dicts with Python?

Spread the love

Sometimes, we want to get a list of values from a list of dicts with Python.

In this article, we’ll look at how to get a list of values from a list of dicts with Python.

How to get a list of values from a list of dicts with Python?

To get a list of values from a list of dicts with Python, we can use list comprehension.

For instance, we write:

dicts = [{
    'value': 'apple',
    'blah': 2
}, {
    'value': 'banana',
    'blah': 3
}, {
    'value': 'cars',
    'blah': 4
}]

values = [d['value'] for d in dicts if 'value' in d]
print(values)

We get the entries in dicts with for d in dicts.

Then we get the value of each entry d with d['value'].

And we only return the entries that has the value key with if 'value' in d.

Therefore, values is ['apple', 'banana', 'cars'].

Conclusion

To get a list of values from a list of dicts with Python, we can use list comprehension.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *