Reputation: 652
I'm try to find the biggest value and corresponding key in a dict totals
, when I code like this, I can get the right answer:
highest_value = 0
highest_key = None
for a_country in totals.keys():
if totals[a_country] > highest_value:
highest_value = totals[a_country]
highest_key = a_country
while I use another way, an error "The variable highest_key is undefined.".
highest_value = 0
highest_key = None
for a_country in totals.keys():
highest_value = totals[a_country] if totals[a_country] > highest_value else highest_value
highest_key = a_country if totals[a_country] > highest_value else highest_key
I'm confused... I think the two codes are the same ....
Upvotes: 0
Views: 1297
Reputation: 658
Considered this as totals:
totals={'20':'10','40':'20','60':'30','80':'40','100':'50','120':'60'}
Explanation:
for your first program I got result like,
Value 60
Key 120
The problem with your second code is in the loop, in first program you are obtaining the highest value and assigning corresponding key to it. But in second you have given
highest_key = a_country if totals[a_country] > highest_value else highest_key
i.e. here highest value now is '60'. So there wont be greater value than the 60, so enters into the else and gives the default none
as result,
if you change it to ==
then you will get the corresponding key.
here it is,
totals={'20':'10','40':'20','60':'30','80':'40','100':'50','120':'60'}
highest_value = 0
highest_key = None
for a_country in totals.keys():
print a_country
highest_value = totals[a_country] if totals[a_country] > highest_value else highest_value
highest_key = a_country if totals[a_country] == highest_value else highest_key
print "Value",highest_value
print "Key",highest_key
Result is,
Value 60
Key 120
Upvotes: 1