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,
Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With