Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Create example list of dictionaries
- records = [{'name':'John', 'address':'6587 S Willow Rd'},
- {'name':'Bill', 'address':'8463 W Empire Ct'},
- {'name':'Frank', 'address':'4513 N Main St'},
- {'name':'Paul', 'address':'18894 E Park Av'}]
- # Just a function to print the records
- def printRecords():
- print('\n*** Name Address ***\n')
- for i in records:
- print(i['name'], i['address'])
- # And now we'll use it to show that the records are not sorted
- printRecords()
- # We can sort addresses by road name using the built in sort function
- # if we restructure each address so that the road name comes first.
- # Then we can apply the same procedure after sorting to create a
- # lookup table.
- def flip(str):
- "moves the first two words of a string to end"
- wordlist = str.split(' ')
- ordered = wordlist[2:] + wordlist[:2]
- return ' '.join(ordered)
- # Now we need a function we can pass a street address to and
- # retrieve the matching dictionary entry.
- def findrecord(s):
- for dict in records:
- if dict['address']==s:
- return dict
- # With those functions in place we can now use list comprehensions
- # to create a list of flipped addresses, sort them, flip them back.
- # This list is then used as a lookup table to sort the list of
- # records.
- adds = [flip(d['address']) for d in records]
- adds.sort()
- adds = [flip(s) for s in adds]
- records=[findrecord(s) for s in adds]
- # And now we'll print the records again to show they are sorted
- printRecords()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement