Python Forum
Sorting and working with dictionary - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Sorting and working with dictionary (/thread-15977.html)



Sorting and working with dictionary - farzankh - Feb-08-2019

Can somebody help with this question?

Given the dictionary, medals, sort it by the medal count. Save the three countries with the highest medal count to the list, top_three.

medals = {'Japan':41, 'Russia':56, 'South Korea':21, 'United States':121, 'Germany':42, 'China':70}
This question may seem very easy to many of you, but i'm curious how you approach it.

Thanks


RE: Sorting and working with dictionary - Larz60+ - Feb-08-2019

first, a dictionary is a hashed table, so by default is not sort-able other than by insertion ordered (which is automatic with versions of python starting with 3.7.
you can, however extract the keys into a list, and then sort the list, effectively creating an ordered index into the dictionary
Example with your dictionary:
>>> medals = {'Japan':41, 'Russia':56, 'South Korea':21, 'United States':121, 'Germany':42, 'China':70}
>>> keys = medals.keys()
>>> for key in keys:
...     print(f'key: {key}, value: {medals[key]}') 
key: Japan, value: 41
key: Russia, value: 56
key: South Korea, value: 21
key: United States, value: 121
key: Germany, value: 42
key: China, value: 70
>>> 
>>> # or by medal count:
>>> klist = []
>>> for key, value in medals.items():
...     klist.append([key, value])
...
>>> klist
[['Japan', 41], ['Russia', 56], ['South Korea', 21], ['United States', 121], ['Germany', 42], ['China', 70]]
>>> sorted(klist, key=lambda klist: klist[1])
[['South Korea', 21], ['Japan', 41], ['Germany', 42], ['Russia', 56], ['China', 70], ['United States', 121]]
>>>



RE: Sorting and working with dictionary - ichabod801 - Feb-08-2019

Iterate over medals.items(), which will give you key/value pairs. Make a list of value/key tuples. Sorting that list will sort by value.


RE: Sorting and working with dictionary - snippsat - Feb-08-2019

Just a advice,you are doing a unnecessary step with klist Larz60+.
>>> medals = {'Japan':41, 'Russia':56, 'South Korea':21, 'United States':121, 'Germany':42, 'China':70}
>>> sorted(medals.items(), key=lambda v: v[1])
[('South Korea', 21),
 ('Japan', 41),
 ('Germany', 42),
 ('Russia', 56),
 ('China', 70),
 ('United States', 121)]
(Feb-08-2019, 03:27 PM)farzankh Wrote: Save the three countries with the highest medal count to the list, top_three.
>>> medals = {'Japan':41, 'Russia':56, 'South Korea':21, 'United States':121, 'Germany':42, 'China':70}
>>> sorted(medals.items(), key=lambda v: v[1], reverse=True)[:3]
[('United States', 121), ('China', 70), ('Russia', 56)]