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