you can filter using the following:
a = list(filter(lambda x: x['name'] == 'IE_Traitement_0A', data['completedapps']))
a will contain a list of all dict that match your filter and then you can sort the the list for the latest one -- using whatever key to sort it by
sorted_a = sorted(a, key=lambda k: k['starttime'])
if you want only one then select the first element of sorted_a assuming it's not empty.
EDIT: use min instead of sorted thanks for the tip @VPfB
min_a = min(a, key=lambda k: k['starttime'])
Answer from gyx-hh on Stack Overflowyou can filter using the following:
a = list(filter(lambda x: x['name'] == 'IE_Traitement_0A', data['completedapps']))
a will contain a list of all dict that match your filter and then you can sort the the list for the latest one -- using whatever key to sort it by
sorted_a = sorted(a, key=lambda k: k['starttime'])
if you want only one then select the first element of sorted_a assuming it's not empty.
EDIT: use min instead of sorted thanks for the tip @VPfB
min_a = min(a, key=lambda k: k['starttime'])
req_json = """{"completedapps" : [ {
"starttime" : 1520863179923,
"id" : "app-20180312145939-0183",
"name" : "IE_Traitement_3",
"cores" : 1,
"user" : "root",
"memoryperslave" : 1024,
"submitdate" : "Mon Mar 12 14:59:39 CET 2018",
"state" : "FINISHED",
"duration" : 212967
}, {
"starttime" : 1520863398147,
"id" : "app-20180312150318-0186",
"name" : "IE_Traitement_3",
"cores" : 1,
"user" : "root",
"memoryperslave" : 1024,
"submitdate" : "Mon Mar 12 15:03:18 CET 2018",
"state" : "FINISHED",
"duration" : 6321
}, {
"starttime" : 1520863387941,
"id" : "app-20180312150307-0185",
"name" : "IE_Traitement_0A",
"cores" : 1,
"user" : "root",
"memoryperslave" : 1024,
"submitdate" : "Mon Mar 12 15:03:07 CET 2018",
"state" : "FINISHED",
"duration" : 149536
} ]}"""
import json
data = json.loads(req_json)
print(sorted(data['completedapps'], key=lambda x: x['starttime'])[0]['id'])
out:
app-20180312145939-0183
Explanation: first get list of dict and sort then by timestamp.
Python Json. Getting only the last element in the json array - Stack Overflow
python - How do I get the last element of a json list? - Stack Overflow
json - How to get the last value from the list using python? - Stack Overflow
Get last item in JSON array with Python - Stack Overflow
I have a json file that looks like this: https://gist.github.com/SirDarknight/95cf48d46c17059a5f42a38ec70c7fa5
What's the best way to get the last object's "Title" key? (In this case: Mercy Black (2019) )
Edit: I'm thinking about wrapping the whole thing in a list and then loading the list
You are replacing the value every time through that loop. You should be adding to the value, instead.
So first create the value as an empty list (before the loop), then on each iteration of the loop, append to that list:
value = []
rec = recipes['Recipes'][0]['Ingredients']
for records in rec:
value.append({'Ingredient ID': records['IngredientID']})
However, having a list of dictionaries, where each dictionary has one single value with the same known key, seems a bit pointless. Depending on your requirements, you probably may want to do either this:
value.append(rec)
or
value.append(records['IngredientID'])
What you're doing right now is that you're redefining value again every loop. You will need to define value before the loop and assign it to an empty list that you can add to.
value = {'Ingredient ID':[]}
for records in rec:
value['Ingredient ID'].append(records['IngredientID'])
You can also define value as a list like this:
value = []
for records in rec:
value.append(records['IngredientID'])
You can do this by accessing the jsonData.seats array by index, index of the last item being equal to jsonData.seats.length-1
simply:
var countryId = jsonData.seats[jsonData.seats.length-1].countryid
NB: Copy of @iuliu.net's code
use DOT at
example.at(-1)
var jsonObject = {
"expirationDate":"April 21, 2017",
"remainingDays":325,
"seats":[{"activeStatus":"S","pid":"TE70","firstName":"TE70","countryid":840},
{"activeStatus":"Y","pid":"TE80","firstName":"TE80","countryid":845}]
}
var lastElement = jsonObject.seats.at(-1).countryid
some_list[-1] is the shortest and most Pythonic.
In fact, you can do much more with this syntax. The some_list[-n] syntax gets the nth-to-last element. So some_list[-1] gets the last element, some_list[-2] gets the second to last, etc, all the way down to some_list[-len(some_list)], which gives you the first element.
You can also set list elements in this way. For instance:
>>> some_list = [1, 2, 3]
>>> some_list[-1] = 5 # Set the last element
>>> some_list[-2] = 3 # Set the second to last element
>>> some_list
[1, 3, 5]
Note that getting a list item by index will raise an IndexError if the expected item doesn't exist. This means that some_list[-1] will raise an exception if some_list is empty, because an empty list can't have a last element.
If your str() or list() objects might end up being empty as so: astr = '' or alist = [], then you might want to use alist[-1:] instead of alist[-1] for object "sameness".
The significance of this is:
alist = []
alist[-1] # will generate an IndexError exception whereas
alist[-1:] # will return an empty list
astr = ''
astr[-1] # will generate an IndexError exception whereas
astr[-1:] # will return an empty str
Where the distinction being made is that returning an empty list object or empty str object is more "last element"-like then an exception object.