Home > OS >  Numerically sort comma delimited string values of nested dictionary in Python
Numerically sort comma delimited string values of nested dictionary in Python

Time:11-04

I have a nested dictionary:

some_dictionary = {
    "sub_dict1": {
        "miles": "5,024,279"
    },
    "sub_dict2": {
        "miles": "733,391"
    },
    "sub_dict3": {
        "miles": "7,151,502"
    }
}

I need to sort some_dictionary by the numerical values of miles so when I display it should be something like this:

"sub_dict2": {"miles": "733,391"},
"sub_dict1": {"miles": "5,024,279"},
"sub_dict3": {"miles": "7,151,502"}

My most recent attempt was:

top = OrderedDict(sorted(some_dictionary.items(), key=lambda x: (x[1], "miles".replace(',', '')))
print(top)

This resulted in a TypeError. I'm pretty lost here, and any help would be appreciated.

CodePudding user response:

Try this instead:

top = dict(sorted(some_dictionary.items(), key= lambda x: int(x[1]["miles"].replace(",", ""))))

You were missing square brackets around "miles" and you probably want to convert the string to int to do the comparison as a number.

Also, since Python 3.7 default dictionary is ordered so you don't have to use OrderedDict

CodePudding user response:

This is a more general approach:

sorted(some_dictionary.items(), key=lambda x: int(''.join([_ for _ in x[1]['miles'] if _.isdigit()])))

using the .isdigit() instead of the .replace is more general. This solution cannot handle float numbers.

  • Related