Python Forum

Full Version: Python 2 to 3 dict sorting
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.
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.
Thank you DeaD_EyE.

I appreciate the full response and the function inclusion!