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?
I'm assuming you meant:
dict.items()iterates over pairs of keys and values, so in yourlambdaexpression,xis not a dictionary like{'value1': ...}, but a tuple like('Name2', {'value1': ...}).You can change
lambda x: x['Index']tolambda 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 changesorted(...)todict(sorted(...)), with two caveats:dictas a variable name, otherwise you will shadow the built-indictconstructor and will get a type error "object is not callable".