【问题标题】:Sorting python dictionary based on value index and in alphabetical order根据值索引和字母顺序对python字典进行排序
【发布时间】: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


【解决方案1】:

你需要一个更复杂的按键功能:

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'])]

【讨论】:

  • 这是完美的。谢谢!我将研究“lambda”函数/项目。我以前没用过,感觉挺好用的。
  • 键可能应该包含 UID 以创建可预测的排序顺序:key=lambda i: (i[1][0].lower(),i[0])
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-26
  • 1970-01-01
  • 1970-01-01
  • 2018-01-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多