Selecting Only Max Value In Python List Of Dicts
I have a list of dicts as follows: [{'server':'8.8.8.8', 'domains':[{'google.com':[{'time':15, 'serial':14}, {'time':78, 'serial':14}]}, {'intuit.com':[{'time':20,
Solution 1:
The solution using built-in max()
function:
import json
# l is your initial list of dictsfor item in l:
for d in item['domains']:
for k, v in d.items():
# whether `serial` numbers are unique
has_uniq_serial = len(set([i['serial'] for i in v])) > 1
d[k] = max(v, key=lambda o: o['serial']) if has_uniq_serial elsemax(v, key=lambda o: o['time'])
# `json.dumps` used for pretty printing of nested dictsprint(json.dumps(l, indent=4))
The output:
[{"server":"8.8.8.8","domains":[{"google.com":{"serial":14,"time":78}},{"intuit.com":{"serial":23,"time":20}}]},{"server":"8.8.4.4","domains":[{"google.com":{"serial":76,"time":92}},{"intuit.com":{"serial":89,"time":45}}]},{"server":"206.67.222.222","domains":[{"google.com":{"serial":76,"time":98}},{"intuit.com":{"serial":59,"time":65}}]}]
Solution 2:
Try this (d is your dict):
for item in d:
for i in item["domains"]:
for k, v in i.items():
c = sorted([(j["time"], j["serial"]) for j in v], key=lambda x: (x[1], x[0]))
i[k] = {"time": c[-1][0], "serial": c[-1][1]}
print d
Solution 3:
You can sort your time-serial list for each domain by your requirement and get the first one, let variable data
be your input list:
defdomain_sorter(d):
defcompare(x, y):
k = y['serial'] - x['serial']
j = y['time'] - x['time']
return k if k != 0else j
returnsorted(d, cmp=compare)
deffilter_domain(domain):
for k, v in domain.items():
return {
k: domain_sorter(v)[0]
}
print [{
"server": e['server'],
"domains": [filter_domain(domain) for domain in e['domains']]
} for e in data]
Post a Comment for "Selecting Only Max Value In Python List Of Dicts"