homer512 icon

Sort dict on missing key

homer512 | PRO | 03/02/15 05:40:39 PM UTC | 0 ⭐ | 801 👁️ | Never ⏰ | []
Python |

780 B

|

None

|

0 👍

/

0 👎

#!/usr/bin/python2
 
 
"""Demonstrates sorting dicts based on keys that might be missing"""
 
 
def main():
    listofdicts = [{'foo': 1, 'bar': 2},
                   {'bar': 3},
                   {'foo': 4, 'bar': 5},
                   ]
    key = 'foo'
    def cmp_(first, second):
        keysfound = [True, True]
        values = []
        for index, item in enumerate((first, second)):
            try:
                value = item[key]
            except KeyError:
                keysfound[index] = False
            else:
                values.append(value)
        if all(keysfound):
            return cmp(*values)
        else:
            return cmp(*reversed(keysfound))
    print sorted(listofdicts, cmp=cmp_)
 
 
if __name__ == '__main__':
    main()

Comments