So I have an array of json data that looks like this:
[{
"first_name": "Joe",
"last_name": "Smith",
"numbers": [1,2,3,4,5]
}, {
"first_name": "Jane",
"last_name": "Doe",
"numbers": [6,4,1,35,2]
}, {
"first_name": "Mike",
"last_name": "Everyman",
"numbers": [8,5,3,2,4,5]
}]
How can I select just the array item where last_name = Doe? I am trying to convert some code I wrote in ruby to python since lambda doesn't support ruby :( My ruby code looks like:
match = data.select {|x| x[:last_name] == 'Doe'}
Which returns:
{
"first_name": "Jane",
"last_name": "Doe",
"numbers": [6,4,1,35,2]
}
Also, I know that wouldn't technically work in ruby since the data is in json form, but I converted it from a hash to json and don't feel like changing it back cause the base idea is still the same.
You can use a generator expression, calling next
on it to supply the first matching item if any:
match = next(d for d in data if d['last_name'] == 'Doe')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With