Sort dictionary alphabetically when the key is a string (name)
dictionary, python, sorting
Solution
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)
Problem
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, some@la.com" [Jack]="32, 122 ble, some@la.com" [Rudy]="42, 123 blj, some@la.com" ``` 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,