当键是字符串(名称)时,按字母顺序对字典进行排序 [英] Sort dictionary alphabetically when the key is a string (name)
问题描述
首先,我知道有很多关于字典排序的帖子,但是我找不到适合我的情况的帖子-而且我只是不了解sorted(... lambda)的内容-因此,请继续.
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.
使用Python 3.x,我有一个像这样的字典:
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 ...
谢谢
推荐答案
一种简单的算法,用于按字母顺序对字典键进行排序,首先使用sorted
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)
这篇关于当键是字符串(名称)时,按字母顺序对字典进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!