【发布时间】:2014-07-28 20:43:47
【问题描述】:
我正在尝试对 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)),但这允许“电子邮件”项目位于最后而不是在“调试”名称之后。见下文:
[('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),但这会导致收到元组而不是字符串的错误。
有什么想法吗?我无法更改字典的形成方式,它必须保持原样。
【问题讨论】:
-
列表的第一个元素是 dict 值是否唯一?也就是说,你可以同时拥有
["CAT", "Software"]和["CAT", "Furry"]吗? -
+1 用于包含您尝试的代码、失败的代码、输入集和观察到的输出集。这是一个有用的问题!
-
格式中的“UID”是唯一的唯一项。可能有两个相同的“名称”。
标签: python sorting dictionary