Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python 2 to 3 dict sorting
#1
Hello,

We have an app that provides a list of searchable multi-layered items originally written in 2.7 and we're converting to 3.8.2. It is hosted on Heroku and is backed by a git repo for those items it displays on its pages.

I have followed the future package tutorial found here https://python-future.org/automatic_conversion.html and have worked through all dependency work.

I have appended 'b' to those elements that were originally referenced as binary-strings in 2.7 and which are need to now be explicitly stated.

I am now caught at sections.sort() line 26 :

def get_sections():
    sections = []
    for path,dirs,files in os.walk(folder):
        print("path: {} dir: {} ".format(path, dirs))
        dirs[:] = [d for d in dirs if not d[0] ==  '.' ]


        for filename in files:

            #   section folder
            if filename.lower() == "readme.md" and len(dirs) != 0 and path != folder:
                #   print os.path.join(path,filename)
                pth = os.path.join(re.sub(folder, '', path), filename)
                pth = pth.lstrip('/')
                with open(os.path.join(path,filename), 'rb') as readme:
                    description = readme.read()
                    description = description.replace(b"##", b"")
                    section_name = path.split(os.path.sep)[-1]
                    section = {
                        "name": section_name,
                        "description": description,
                        "slug": urllib.parse.quote(section_name),
                        "examples": []
                    }
                    sections.append(section)
    sections.sort()
    return sections





The error I get is "TypeError: '<' not supported between instances of 'dict' and 'dict'"

Since finding out Python 3 doesn't support sorting dicts the same way Python 2 does I changed it to
sections = {k: disordered[k] for k in sorted(sections)}

and still get "TypeError: '<' not supported between instances of 'dict' and 'dict'"

Any general guidance on what is happening between the dictionaries I'm creating and sorting would be much appreciated.
Reply
#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
#3
Thank you DeaD_EyE.

I appreciate the full response and the function inclusion!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  String index out of bounds ( Python : Dict ) kommu 2 2,350 Jun-25-2020, 08:52 PM
Last Post: menator01
  Sort a dict in dict cherry_cherry 4 62,339 Apr-08-2020, 12:25 PM
Last Post: perfringo
  Python list - group by dict key karthidec 2 9,331 Nov-25-2019, 06:58 AM
Last Post: buran
  Sorting a copied list is also sorting the original list ? SN_YAZER 3 2,991 Apr-11-2019, 05:10 PM
Last Post: SN_YAZER
  Python - sorting algorithms hrca 3 3,111 Nov-06-2018, 07:06 PM
Last Post: hrca
  Conditional sorting in Python amirt 1 6,367 Jul-05-2018, 01:32 PM
Last Post: buran
  Python 3.6 dict key iteration order insearchofanswers87 7 5,285 May-22-2018, 05:33 PM
Last Post: snippsat
  Python 2.7 Addition to dict is too slow VolanD 6 3,971 May-04-2018, 09:24 AM
Last Post: Gribouillis
  Sorting values calculated in python stumunro 4 3,899 Sep-13-2017, 06:09 AM
Last Post: nilamo
  sorting nested dict according to values merlem 6 17,467 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