given a list of dictionaries with all the same format and fields, calculate the rank of the dictionary based on a field. In the example below, I want to print the age ranking of each person
Ex:
dicts = [
{
'name': 'John',
'age': 23
},
{
'name': 'Sue',
'age': 29
},
...
]
for person in dicts:
age_rank = ...
print(f"{person['name']} is age-rank {age_rank}")
The oldest person should be rank 1, the next highest is rank 2, etc.
Edit: is there any way to keep the for loop untouched?
CodePudding user response:
Iterate over your values sorted by age descending, then combine with enumerate
to generate the iteration index
for rank, person in enumerate(sorted(dicts, key=lambda x: x['age'], reverse=True), start=1):
print(f"{person['name']} is age-rank {rank}")
CodePudding user response:
It depends on what you want to do after but maybe using Pandas
could be a good choice:
import pandas as pd
df = pd.DataFrame(dicts)
df['age_rank'] = df['age'].rank(method='dense').astype(int)
print(df)
# Output
name age age_rank
0 John 23 1
1 Sue 29 2
Update
I am wanting to keep the for loop in the exact format that I've described. i.e. keep for person in dicts untouched
for person in dicts:
age_rank = sum(person['age'] < x['age'] for x in dicts) 1
print(f"{person['name']} is age-rank {age_rank}")
# Output
John is age-rank 2
Sue is age-rank 1
CodePudding user response:
You can sort base age
of each dict
in list
then print as you like with for-loop
on result of sort:
dicts = [
{
'name': 'John',
'age': 23
},
{
'name': 'Sue',
'age': 29
},
]
for rnk , dct in enumerate(sorted(dicts, key=lambda x: x['age'], reverse=True)):
print(f"{dct['name']} is age-rank {rnk 1}")
Update Without changing for-loop
in the Question First sorting age, at the end use index for finding the rank from the sorting list.
srt_ages = sorted([dct['age'] for dct in dicts], reverse=True)
for person in dicts:
age_rank = srt_ages.index(person['age']) 1
print(f"{person['name']} is age-rank {age_rank}")
Sue is age-rank 1
John is age-rank 2