Advertisement
homer512

Sort dict on missing key

Mar 2nd, 2015
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.78 KB | None | 0 0
  1. #!/usr/bin/python2
  2.  
  3.  
  4. """Demonstrates sorting dicts based on keys that might be missing"""
  5.  
  6.  
  7. def main():
  8.     listofdicts = [{'foo': 1, 'bar': 2},
  9.                    {'bar': 3},
  10.                    {'foo': 4, 'bar': 5},
  11.                    ]
  12.     key = 'foo'
  13.     def cmp_(first, second):
  14.         keysfound = [True, True]
  15.         values = []
  16.         for index, item in enumerate((first, second)):
  17.             try:
  18.                 value = item[key]
  19.             except KeyError:
  20.                 keysfound[index] = False
  21.             else:
  22.                 values.append(value)
  23.         if all(keysfound):
  24.             return cmp(*values)
  25.         else:
  26.             return cmp(*reversed(keysfound))
  27.     print sorted(listofdicts, cmp=cmp_)
  28.  
  29.  
  30. if __name__ == '__main__':
  31.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement