homer512 icon

Python3: Sort dict on missing key

homer512 | PRO | 03/02/15 06:41:02 PM UTC | 0 ⭐ | 671 👁️ | Never ⏰ | []
Python |

610 B

|

None

|

0 👍

/

0 👎

#!/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()

Comments