Sorting list of dicts by value of a key (or default-value, if key is missing)

Imagine that you have to sort a list of dicts, by the value of a particular key. Note that the key might be missing from some of the dicts, in which case you default to the value of that key to being 0.

sample input

  • input = [{'a': 1, 'b': 2}, {'a': 10, 'b': 3}, {'b': 5}]

sample output (sorted by value of key 'a')

  • [{'b': 5}, {'a': 1, 'b': 2}, {'a': 10, 'b': 3}]

note that {'b': 5} is first in the sort-order because it has the lowest value for 'a' (0)

I would've used input.sort(key=operator.itemgetter('a')), if all the dicts were guaranteed to have the key 'a'. Or I could convert the input dicts to collections.defaultdict and then sort.

Is there a way to do this in-place without having to creating new dicts or updating the existing dicts? Can operator.itemgetter handle missing keys?


7 Likes1.35 GEEK