I have an output that is a list of dicts:
output:
[{'name' : 'andres', 'age': 10},
{'name' : 'paul', 'age' :20}]
Now I want to filter this out to get the name of who is older than a THRESOLH.This threshold comes from a json file that has this structure:
{"NAMES":['andres', 'paul'], "THRESHOLD":{'andres':14, 'paul': 16}}
The expected output is: ['paul']
because `paul's age in output is 20 and the threshold for him is 16, so 20 > 16 ok!
What I am doing:
THRESHOLD_ = json_file_name['THESHOLD]
NAMES_ = json_file_name['NAMES']
and then:
final_output = [dict(name=i, bio_age for i,w in output if i['age'] >= THRESHOLD_.get(i)]
This is not working:
I want as final output:
1 - dictionary {'name':age'} of people with age higher than it's age limit in json_file
2 - list of name of people with age higher than it's age limit in json_file
{"paul":20}, ['paul']
CodePudding user response:
Just use a dictionary comprehension - https://akuiper.com/console/iVq4s2J3kwdR
lst = [{'name' : 'andres', 'age': 10},
{'name' : 'paul', 'age' :20}]
thresh = {"NAMES":['andres', 'paul'], "THRESHOLD":{'andres':14, 'paul': 16}}
{d['name']: d['age'] for d in lst if d['age'] > thresh['THRESHOLD'].get(d['name'], 0)}
# {'paul': 20}
To get the keys:
filtered = {d['name']: d['age'] for d in lst if d['age'] > thresh['THRESHOLD'].get(d['name'], 0)}
list(filtered.keys())
# ['paul']