Advertisement
homer512

Python3: Sort dict on missing key

Mar 2nd, 2015
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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.             return (not missingfirst, )
  13.         else:
  14.             return (missingfirst, value)
  15.     return keyfun
  16.  
  17. def main():
  18.     listofdicts = [{'foo': 1, 'bar': 2},
  19.                    {'bar': 3},
  20.                    {'foo': 4, 'bar': 5},
  21.                    ]
  22.     print(sorted(listofdicts, key=make_keyfun('foo', missingfirst=False)))
  23.  
  24.  
  25. if __name__ == '__main__':
  26.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement