Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort dictionary alphabetically when the key is a string (name)

First, I know there are a LOT of posts on dictionary sorting but I couldn't find one that was exactly for my case - and I am just not understanding the sorted(...lambda) stuff - so here goes.

Using Python 3.x I have a dictionary like this:

dictUsers[Name] = namedTuple(age, address, email, etc...)

So as an example my dictionary looks like

[John]="29, 121 bla, [email protected]"
[Jack]="32, 122 ble, [email protected]"
[Rudy]="42, 123 blj, [email protected]"

And right now for printing I do the following (where response is a dictionary):

for keys, values in response.items():
    print("Name= " + keys)
    print ("   Age= " + values.age)
    print ("   Address= " + values.address)
    print ("   Phone Number= " + values.phone)

And when the user asks to print out the database of users I want it to print in alphabetical order based on the "name" which is used as the KEY.

I got everything to work - but it isn't sorted - and before starting to sort it manually I thought maybe there was a built-in way to do it ...

Thanks,

like image 673
JSchwartz Avatar asked Jul 14 '14 02:07

JSchwartz


People also ask

Can you sort a dictionary based on keys?

Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.

Can you sort a dictionary by value in Python?

To sort a dictionary by value in Python you can use the sorted() function. Python's sorted() function can be used to sort dictionaries by key, which allows for a custom sorting method. sorted() takes three arguments: object, key, and reverse. Dictionaries are unordered data structures.


1 Answers

simple algorithm to sort dictonary keys in alphabetical order, First sort the keys using sorted

sortednames=sorted(dictUsers.keys(), key=lambda x:x.lower())

for each key name retreive the values from the dict

for i in sortednames:
   values=dictUsers[i]
   print("Name= " + i)
   print ("   Age= " + values.age)
   print ("   Address= " + values.address)
   print ("   Phone Number= " + values.phone)
like image 100
sundar nataraj Avatar answered Oct 22 '22 01:10

sundar nataraj