Search code examples
pythonsortingdictionarynamed

How do I sort a Python Dictionary by a named value


I have a dictionary 'dict' like so:

{'Name1' : {'value1' : 3.0, 'value2' : 1.4, 'Index' : 2 },  
 'Name2' : {'value1' : 5.0, 'value2' : 0.1, 'Index' : 1 },  
 ...
}

How would I sort the dictionary into a new one, based on the 'Index' field? So I want to end up as:

{'Name2' : {'value1' : 5.0, 'value2' : 0.1, 'Index' : 1 },  
 'Name1' : {'value1' : 3.0, 'value2' : 1.4, 'Index' : 2 },  
 
 ...
}

I have tried

new_dict = sorted(dict.items(), key=lambda x: x['Index'])

but Python objects to the str as the slice.

Apart from the clunky method of iterating through and appending each item to a new dictionary what is the recommended method please?


Solution

  • I'm assuming you meant:

    {'Name1' : {'value1': 3.0, 'value2': 1.4, 'Index': 2 },  
     'Name2' : {'value1': 5.0, 'value2': 0.1, 'Index': 1 },  
     ...
    }
    

    dict.items() iterates over pairs of keys and values, so in your lambda expression, x is not a dictionary like {'value1': ...}, but a tuple like ('Name2', {'value1': ...}).

    You can change lambda x: x['Index'] to lambda x: x[1]['Index'] (i.e., first get the second item of the tuple (which should now be the nested dictionary), then get the 'Index' value in that dictionary.

    Next, sorted() will give you a list of key, value pairs (which may be appropriate). If you really want a dictionary, you can change sorted(...) to dict(sorted(...)), with two caveats:

    • In older Python versions this will lose the sorting again (see here).
    • Don't use dict as a variable name, otherwise you will shadow the built-in dict constructor and will get a type error "object is not callable".