Advertisement
Guest User

address sorting example

a guest
Feb 21st, 2014
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.51 KB | None | 0 0
  1. # Create example list of dictionaries
  2. records = [{'name':'John', 'address':'6587 S Willow Rd'},
  3.     {'name':'Bill', 'address':'8463 W Empire Ct'},
  4.     {'name':'Frank', 'address':'4513 N Main St'},
  5.     {'name':'Paul', 'address':'18894 E Park Av'}]
  6.  
  7. # Just a function to print the records
  8. def printRecords():
  9.     print('\n*** Name Address ***\n')
  10.     for i in records:
  11.         print(i['name'], i['address'])
  12.        
  13. # And now we'll use it to show that the records are not sorted
  14. printRecords()
  15.  
  16. # We can sort addresses by road name using the built in sort function
  17. # if we restructure each address so that the road name comes first.
  18. # Then we can apply the same procedure after sorting to create a
  19. # lookup table.
  20.  
  21. def flip(str):
  22.     "moves the first two words of a string to end"
  23.     wordlist = str.split(' ')
  24.     ordered = wordlist[2:] + wordlist[:2]
  25.     return ' '.join(ordered)
  26.  
  27. # Now we need a function we can pass a street address to and
  28. # retrieve the matching dictionary entry.
  29.    
  30. def findrecord(s):
  31.     for dict in records:
  32.         if dict['address']==s:
  33.             return dict
  34.  
  35. # With those functions in place we can now use list comprehensions
  36. # to create a list of flipped addresses, sort them, flip them back.
  37. # This list is then used as a lookup table to sort the list of
  38. # records.
  39.  
  40. adds = [flip(d['address']) for d in records]
  41. adds.sort()
  42. adds = [flip(s) for s in adds]
  43. records=[findrecord(s) for s in adds]
  44.  
  45. # And now we'll print the records again to show they are sorted
  46. printRecords()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement