NewToJS
NewToJS

Reputation: 2101

Python: How to filter a list of dictionaries to get all the values of one key

I have a list of dictionaries in python:

thedata = [{'date': '2002-02', 'data': 2.0}, 
           {'date': '2002-03', 'data': 2.0017}...]

How do I make a list of just the 'data' values?:

[2.0, 2.0017...]

I've tried:

justFigures = list(filter(lambda x: x["data"], thedata))

Upvotes: 3

Views: 1159

Answers (3)

Ari Gold
Ari Gold

Reputation: 1548

thedata = [{'date': '2002-02', 'data': 2.0}, 
           {'date': '2002-03', 'data': 2.0017}]

# back to your own way, lambda
# py 2
print map(lambda a : a["data"], thedata)

# py 3
print (list(map(lambda a : a["data"], thedata)))

>>> [2.0, 2.0017]

Upvotes: 0

wpercy
wpercy

Reputation: 10090

I would use a list comprehension

In [1]: thedata = [{'date': '2002-02', 'data': 2.0},
                   {'date': '2002-03', 'data': 2.0017}]

In [2]: just_figures = [ d['data'] for d in thedata ]

In [3]: just_figures
Out[3]: [2.0, 2.0017]

Upvotes: 5

Mohammad Yusuf
Mohammad Yusuf

Reputation: 17074

You can try like so:

thedata = [{'date': '2002-02', 'data': 2.0}, 
           {'date': '2002-03', 'data': 2.0017}]

print([a['data'] for a in thedata])

Output:

[2.0, 2.0017]

Upvotes: 8

Related Questions