#!/usr/bin/python3 """Demonstrates sorting dicts based on keys that might be missing""" def make_keyfun(key, missingfirst=True): def keyfun(item): try: value = item[key] except KeyError: return (not missingfirst, ) else: return (missingfirst, value) return keyfun def main(): listofdicts = [{'foo': 1, 'bar': 2}, {'bar': 3}, {'foo': 4, 'bar': 5}, ] print(sorted(listofdicts, key=make_keyfun('foo', missingfirst=False))) if __name__ == '__main__': main()