I have a dictionary which contains some racers as shown below:
dict = {('Richard','Ringer'):['Germany',(2,11,27)], \
('Eliud','Kipchoge'):['Kenya',(2,8,38)], \
('Yavuz','Agrali'):['Turkey',(2,15,5)]
}
#('Richard','Ringer')=name
#'Germany'=country
#(2,11,27)=complation time of the race; hours, minutes and seconds.
I want to put the key values (which are name and surname) and time which calculated in seconds, sort them in ascending order:
for i in dict:
name=i[0]
surname=i[1]
liselement=name+" "+surname
country=dict[i][0]
hours=dict[i][1][0]
minutes=dict[i][1][1]
seconds=dict[i][1][2]
inseconds=(hours*60*60)+minutes*60+seconds
dictmedal[liselement,country]=inseconds
sorted_dictmedal = sorted(dictmedal.items(),key=lambda kv:kv[0])
for nth,key in zip(('Gold Medal:','Silver Medal:','Bronze Medal:'),dictmedal):
print(nth,*key)
for nth,key in zip(('Gold Medal:','Silver Medal:','Bronze Medal:'),sorted_dictmedal):
print(nth,*key)
Output:
Gold Medal: Richard Ringer Germany
Silver Medal: Eliud Kipchoge Kenya
Bronze Medal: Yavuz Agrali Turkey
Gold Medal: ('Eliud Kipchoge', 'Kenya') 7718
Silver Medal: ('Richard Ringer', 'Germany') 7887
Bronze Medal: ('Yavuz Agrali', 'Turkey') 8105
Is there a way to make the sorted_dictmedal look like dictmedal output? Also, is there a way to put a comma between name and city?
Gold Medal: Richard Ringer, Germany
>Solution :
Maybe you could use tuple unpacking:
racers = {
('Richard', 'Ringer'): ['Germany', (2, 11, 27)],
('Eliud', 'Kipchoge'): ['Kenya', (2, 8, 38)],
('Yavuz', 'Agrali'): ['Turkey', (2, 15, 5)],
}
medals = {}
for (first_name, last_name), [country, (hours, minutes, seconds)] in racers.items():
time_in_seconds = hours * 60 * 60 + minutes * 60 + seconds
racer_key = f'{first_name} {last_name}, {country}'
medals[racer_key] = time_in_seconds
print('Unsorted:')
for medal, (racer_key, time) in zip(('Gold Medal:', 'Silver Medal:', 'Bronze Medal:'), medals.items()):
print(medal, racer_key)
print('\nSorted:')
for medal, (racer_key, time) in zip(('Gold Medal:', 'Silver Medal:', 'Bronze Medal:'), sorted(medals.items(), key=lambda m: m[1])):
print(medal, racer_key)
Output:
Unsorted:
Gold Medal: Richard Ringer, Germany
Silver Medal: Eliud Kipchoge, Kenya
Bronze Medal: Yavuz Agrali, Turkey
Sorted:
Gold Medal: Eliud Kipchoge, Kenya
Silver Medal: Richard Ringer, Germany
Bronze Medal: Yavuz Agrali, Turkey