Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python 2 to 3 dict sorting
#2
Funny, I even did not know that you can't do that.
But there is a solution. You can use the key-function to convert
the keys to a tuple or list. Then this object is used for comparison.

sorted([{-21: None, 2: None}, {-100: None, -2: None}], key=lambda x: tuple(x.keys()))
The key-function can also written as normal function:
def dict_sort(mapping):
    return tuple(mapping.keys())
sorted([{-21: None, 2: None}, {-100: None, -2: None}], key=dict_sort)
You can also choose a key, which you want to use for sorting or you can select values to sort the dict.
It depends on what you want to reach.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
Python 2 to 3 dict sorting - by joshuaprocious - May-13-2020, 11:24 PM
RE: Python 2 to 3 dict sorting - by DeaD_EyE - May-14-2020, 07:09 AM
RE: Python 2 to 3 dict sorting - by joshuaprocious - May-14-2020, 03:28 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  String index out of bounds ( Python : Dict ) kommu 2 2,429 Jun-25-2020, 08:52 PM
Last Post: menator01
  Python list - group by dict key karthidec 2 9,477 Nov-25-2019, 06:58 AM
Last Post: buran
  Sorting a copied list is also sorting the original list ? SN_YAZER 3 3,137 Apr-11-2019, 05:10 PM
Last Post: SN_YAZER
  Python - sorting algorithms hrca 3 3,206 Nov-06-2018, 07:06 PM
Last Post: hrca
  Conditional sorting in Python amirt 1 6,488 Jul-05-2018, 01:32 PM
Last Post: buran
  Python 3.6 dict key iteration order insearchofanswers87 7 5,414 May-22-2018, 05:33 PM
Last Post: snippsat
  Python 2.7 Addition to dict is too slow VolanD 6 4,114 May-04-2018, 09:24 AM
Last Post: Gribouillis
  Sorting values calculated in python stumunro 4 4,027 Sep-13-2017, 06:09 AM
Last Post: nilamo
  sorting nested dict according to values merlem 6 17,704 Apr-01-2017, 10:01 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

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