SHOW:
|
|
- or go back to the newest paste.
| 1 | - | #!/usr/bin/python2 |
| 1 | + | #!/usr/bin/python3 |
| 2 | ||
| 3 | ||
| 4 | """Demonstrates sorting dicts based on keys that might be missing""" | |
| 5 | ||
| 6 | ||
| 7 | def make_keyfun(key, missingfirst=True): | |
| 8 | def keyfun(item): | |
| 9 | try: | |
| 10 | value = item[key] | |
| 11 | except KeyError: | |
| 12 | - | key = 'foo' |
| 12 | + | return (not missingfirst, ) |
| 13 | - | def cmp_(first, second): |
| 13 | + | |
| 14 | - | keysfound = [True, True] |
| 14 | + | return (missingfirst, value) |
| 15 | - | values = [] |
| 15 | + | return keyfun |
| 16 | - | for index, item in enumerate((first, second)): |
| 16 | + | |
| 17 | - | try: |
| 17 | + | |
| 18 | - | value = item[key] |
| 18 | + | |
| 19 | - | except KeyError: |
| 19 | + | |
| 20 | - | keysfound[index] = False |
| 20 | + | |
| 21 | - | else: |
| 21 | + | |
| 22 | - | values.append(value) |
| 22 | + | print(sorted(listofdicts, key=make_keyfun('foo', missingfirst=False)))
|
| 23 | - | if all(keysfound): |
| 23 | + | |
| 24 | - | return cmp(*values) |
| 24 | + | |
| 25 | if __name__ == '__main__': | |
| 26 | - | return cmp(*reversed(keysfound)) |
| 26 | + |