andyguest13
andyguest13

Reputation: 23

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?

Upvotes: 0

Views: 252

Answers (2)

bobah
bobah

Reputation: 18864

Python dict is a hashed associative container, it cannot be sorted.

Python 3 dict is insertion-ordered, so if you sort a copy of items collections of the original dictionary and comprehend it back into a dict it will be in the order you need.

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

y = {k: v for k, v in sorted(x.items(), key=lambda item: item[1]['Index'])}

Also, have you seen OrderedDict?

Upvotes: 3

mkrieger1
mkrieger1

Reputation: 23255

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".

Upvotes: 2

Related Questions