Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python get json array item by matching value [duplicate]

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.

like image 790
cashman04 Avatar asked Sep 01 '25 18:09

cashman04


1 Answers

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')
like image 177
Moses Koledoye Avatar answered Sep 04 '25 10:09

Moses Koledoye