Python Forum
Sorting and working with dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sorting and working with dictionary
#2
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]]
>>>
Reply


Messages In This Thread
Sorting and working with dictionary - by farzankh - Feb-08-2019, 03:27 PM
RE: Sorting and working with dictionary - by Larz60+ - Feb-08-2019, 03:56 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020