I have list of dictionaries that I am pulling from a ticketing system that contains the name and timestamp of the ticket.
There are cases where multiple tickets are entered for the same user and would like to filter this list to only append the 'latest' timestamp to the list, rather than all occurrences.
My function that gathers the data is:
def get_onboarded_users():
# The ticket that it is retrieving looks something like this:
# "(IT) - Onboarding Initiated - Bill Bob"
print("Collecting Onboarded Users", end="")
url = 'https://********************/api/v3/requests'
headers = {"authtoken": "*********************************"}
rtn = []
input_data = '''{
"list_info": {
"row_count": 5000,
"start_index": 1,
"sort_field": "subject",
"sort_order": "asc",
"get_total_count": true,
"search_fields": {
"subject": "(IT) - Onboarding Initiated"
}
}
}'''
params = {'input_data': input_data}
response = requests.get(url, headers=headers, params=params)
i = json.loads(response.text)
user_requests = i['requests']
onboarded_users = {}
for user_request in user_requests:
subject = user_request['subject'].upper()
create_date = req['created_time']['value']
user = subject.split(' - ')
onboarded_users['Name'] = user[2]
onboarded_users['Date'] = int(create_date) / 1000
rtn.append(onboarded_users.copy())
print(" - Complete")
return rtn
My API call returns something that looks like this:
[
{ "Name": "Bill Bob", "Date": "1640012025.813" },
{ "Name": "Rob Smith", "Date": "1651670375.795" },
{ "Name": "Bill Bob", "Date": "1651670375.795" },
{ "Name": "Rob Smith", "Date": "1640012025.813" }
]
and would like it to look like this:
[
{ "Name": "Rob Smith", "Date": "1651670375.795" },
{ "Name": "Bill Bob", "Date": "1651670375.795" }
]
CodePudding user response:
Try:
[item for item in a if item['Date'] == max(a, key=lambda x: x['Date'])]
CodePudding user response:
Try this:
max_lst = max(lst, key=lambda x: x['Date'])
res = [l for l in lst if l['Date'] == max_lst['Date']]
print(res)
Output:
[
{'Name': 'Rob Smith', 'Date': '1651670375.795'},
{'Name': 'Bill Bob', 'Date': '1651670375.795'}
]