Sort Python Dictionaries by Value

As most of Python programmer knows that dictionaries is like associative array found in different languages. Dictionaries index by key and it is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.

sha = {'West Midlands Strategic Health Authority':'West Midlands Strategic Health Authority','South Central Strategic Health Authority':'South Central Strategic Health Authority','North West Strategic Health Authority':'North West Strategic Health Authority','Yorkshire and the Humber Strategic Health Authority':'Yorkshire and the Humber Strategic Health Authority','East Midlands Strategic Health Authority':'East Midlands Strategic Health Authority','East of England Strategic Health Authority':'East of England Strategic Health Authority','London Strategic Health Authority':'London Strategic Health Authority','South East Coast Strategic Health Authority':'South East Coast Strategic Health Authority','South West Strategic Health Authority':'South West Strategic Health Authority','Health and Social Care Board':'Northern Ireland','National Advisory Board':'Wales','Scotland':'Scotland'}
items = [(v, k) for k, v in sha.items()]
items.sort()
items = [(k, v) for v, k in items]
return items

If you like to use sorting in different order then you use items.reverse().

Share

Comments

  1. Here’s a slightly shorter version that is more efficient.

    items = sorted(sha.items(), key=lambda i: i[1])

    We use the key argument for the sorted function which allows us to define a function to use on each item which returns the value to sort by, in the case the 2nd element of each item in the dictionary.

    This makes the need to build a sequence of value/item pairs redundant, so we can reference sha.items() directly. Also this means we don’t need the final step of rebuilding the sequence as key/value pairs from value/key pairs.

Leave a Reply

Your email address will not be published. Required fields are marked *