Home > Mobile >  How to sort a nested dictionary by letter?
How to sort a nested dictionary by letter?

Time:02-15

I have a problem. I have a dict. This contains abbreviations. This dict should be sorted according to the shortForm. First all short forms with A, B, ..., Z. I have tried it with sorted, but this does not work as desired. Now my question is how can I sort my dict by letters so that I get the desired output (see below)?

Code

final_output = {
    "abbreviation_knmi": {
        "symbol": "knmi",
        "shortform": "KNMI",
        "longform": "Koninklijk Nederlands Meteorologisch Instituut"
    },
    "abbreviation_fbi": {
        "symbol": "fbi",
        "shortform": "FBI",
        "longform": "Federal Bureau of Investigation"
    },
    "abbreviation_eg": {
        "symbol": "eg",
        "shortform": "e.g.",
        "longform": "For example"
    }
}
sorted_list = sorted(final_output.keys(), key=lambda x: (final_output[x]['shortform']))
print(sorted_list)

[OUT] ['abbreviation_knmi', 'abbreviation_fbi', 'abbreviation_eg']

Desired Output Dict

{
    "abbreviation_eg": {
        "symbol": "eg",
        "shortform": "e.g.",
        "longform": "For example"
    }
    "abbreviation_fbi": {
        "symbol": "fbi",
        "shortform": "FBI",
        "longform": "Federal Bureau of Investigation"
    },   
    "abbreviation_knmi": {
        "symbol": "knmi",
        "shortform": "KNMI",
        "longform": "Koninklijk Nederlands Meteorologisch Instituut"
    },
}

CodePudding user response:

Seems its already answered here

final_output = {
    "abbreviation_knmi": {
        "symbol": "knmi",
        "shortform": "KNMI",
        "longform": "Koninklijk Nederlands Meteorologisch Instituut"
    },
    "abbreviation_fbi": {
        "symbol": "fbi",
        "shortform": "FBI",
        "longform": "Federal Bureau of Investigation"
    },
    "abbreviation_eg": {
        "symbol": "eg",
        "shortform": "e.g.",
        "longform": "For example"
    }
}

sorted_dict = dict(sorted(final_output.items(), key=lambda x: x[1]['shortform']))
print(sorted_dict)

Output:

{   'abbreviation_eg': {   'longform': 'For example',
                           'shortform': 'e.g.',
                           'symbol': 'eg'},
    'abbreviation_fbi': {   'longform': 'Federal Bureau of Investigation',
                            'shortform': 'FBI',
                            'symbol': 'fbi'},
    'abbreviation_knmi': {   'longform': 'Koninklijk Nederlands Meteorologisch '
                                         'Instituut',
                             'shortform': 'KNMI',
                             'symbol': 'knmi'}}
  • Related