How do I sort a list of dictionaries by last name of the dictionary in Python? -


i need write sort_contacts function takes dictionary of contacts parameter , returns sorted list of contacts, each contact tuple.

the contacts dictionary passed function has contact name key, , value tuple containing phone number , email contact.

contacts = {name: (phone, email), name: (phone, email), etc.}

the sort_contacts function should create new, sorted (by last name) list of tuples representing of contact info (one tuple each contact) in dictionary. should return list calling function.

for example, given dictionary argument of:

    {("horney, karen": ("1-541-656-3010", "karen@psychoanalysis.com"),     "welles, orson": ("1-312-720-8888", "orson@notlive.com"),     "freud, anna": ("1-541-754-3010", "anna@psychoanalysis.com")} 

sort_contacts should return this:

    [('freud, anna', '1-541-754-3010', 'anna@psychoanalysis.com'),      ('horney, karen', '1-541-656-3010', 'karen@psychoanalysis.com'),      ('welles, orson', '1-312-720-8888', 'orson@notlive.com')]** 

you can add key , value , sort:

>>> sorted((k,)+v k, v in contacts.items()) [('freud, anna', '1-541-754-3010', 'anna@psychoanalysis.com'),  ('horney, karen', '1-541-656-3010', 'karen@psychoanalysis.com'),  ('welles, orson', '1-312-720-8888', 'orson@notlive.com')] 

if don't care nested tuple can simply:

>>> sorted(contacts.items()) [('freud, anna', ('1-541-754-3010', 'anna@psychoanalysis.com')),  ('horney, karen', ('1-541-656-3010', 'karen@psychoanalysis.com')),  ('welles, orson', ('1-312-720-8888', 'orson@notlive.com'))] 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -