Reputation: 95
What I would like to do is loop through my_family and return the member with the highest Age.
my_family = {
"member1": {"Name":"Person1","Gender": "Male","Age": 24},
"member2": {"Name":"Person2","Gender": "Male","Age": 32},
"member3": {"Name":"Person3","Gender": "Female","Age": 62}
}
My attempt is below:
k = my_family.keys()
v = my_family.values()
def highAge():
for k,v in my_family.items():
if "Age" in my_family.items():
print("Age found")
else:
print("Failed")
highAge()
The current output is Failed.
Upvotes: 0
Views: 58
Reputation: 53
You can also sort your dictionary by the age and take the last item
my_family = {
"member1": {"Name":"Person1","Gender": "Male","Age": 24},
"member3": {"Name":"Person3","Gender": "Female","Age": 62},
"member2": {"Name":"Person2","Gender": "Male","Age": 32},
}
my_family_sorted_by_age = sorted(my_family.items(), key=lambda item: item[1]["Age"])
print(my_family_sorted_by_age[-1])
Upvotes: 0
Reputation: 189
If you don't care about keys then here is a simple solution to your problem.
my_family = {
"member1": {"Name":"Person1","Gender": "Male","Age": 24},
"member2": {"Name":"Person2","Gender": "Male","Age": 32},
"member3": {"Name":"Person3","Gender": "Female","Age": 62}
}
person_with_max_age = max(my_family.values(), key=lambda f: f["Age"])
print(person_with_max_age)
>> {'Name': 'Person3', 'Gender': 'Female', 'Age': 62}
Upvotes: 2
Reputation: 14201
The quick fix:
Your first 2 lines are superfluous, delete them:
k = my_family.keys()
v = my_family.values()
Then in the if
statement change my_family.items()
to v
, and append the break
command. So your full program will be
def highAge():
for k, v in my_family.items():
if "Age" in v:
print("Age found")
break
else:
print("Failed")
highAge()
Upvotes: 1