我正在尝试对python字典进行排序并遇到一些问题。字典采用以下格式:{UID:Name,Type}。
dic1={"720155": ["CAT", "Software"], "356d05": ["ESF", "Software"], "3b3758": ["DBA", "Software"], "9649db": ["Fun", "Software"], "96493f": ["Eagle", "Software"], "99701d": ["Pas", "Software"], "964971": ["Debug", "Software"], "b6f315": ["Bap", "Software"], "a0a824": ["Server", "Software"], "1e00sa": ["Adobe", "Software"], "8c8dd2": ["EXIT", "Software"], "cc1dfg": ["email", "Software"]}
我使用sorted(dic1.iteritems(), key=operator.itemgetter(1))
但这允许“email”项目是最后一个而不是“Debug”名称之后。见下文:
[('1e00sa', ['Adobe', 'Software']),
('b6f315', ['Bap', 'Software']),
('720155',['CAT', 'Software']),
('3b3758', ['DBA', 'Software']),
('964971', ['Debug', 'Software']),
('356d05', ['ESF', 'Software']),
('8c8dd2', ['EXIT', 'Software']),
('96493f', ['Eagle', 'Software']),
('9649db', ['Fun', 'Software']),
('99701d', ['Pas', 'Software']),
('a0a824', ['Server', 'Software']),
('cc1dfg', ['email', 'Software'])]
我尝试使用sorted(sorted(dic1.iteritems(), key=operator.itemgetter(1)), key=str.lower)
,但这会产生一个错误,即收到了一个元组而不是一个字符串。
有什么想法吗?我无法改变字典的形成方式,它必须保持原样。
答案 0 :(得分:3)
您需要更复杂的关键功能:
sorted(dic1.iteritems(), key=lambda i: i[1][0].lower())
这对值的第一个元素进行排序,小写。
演示:
>>> from pprint import pprint
>>> dic1={"720155": ["CAT", "Software"], "356d05": ["ESF", "Software"], "3b3758": ["DBA", "Software"], "9649db": ["Fun", "Software"], "96493f": ["Eagle", "Software"], "99701d": ["Pas", "Software"], "964971": ["Debug", "Software"], "b6f315": ["Bap", "Software"], "a0a824": ["Server", "Software"], "1e00sa": ["Adobe", "Software"], "8c8dd2": ["EXIT", "Software"], "cc1dfg": ["email", "Software"]}
>>> pprint(sorted(dic1.iteritems(), key=lambda i: i[1][0].lower()))
[('1e00sa', ['Adobe', 'Software']),
('b6f315', ['Bap', 'Software']),
('720155', ['CAT', 'Software']),
('3b3758', ['DBA', 'Software']),
('964971', ['Debug', 'Software']),
('96493f', ['Eagle', 'Software']),
('cc1dfg', ['email', 'Software']),
('356d05', ['ESF', 'Software']),
('8c8dd2', ['EXIT', 'Software']),
('9649db', ['Fun', 'Software']),
('99701d', ['Pas', 'Software']),
('a0a824', ['Server', 'Software'])]