python - 根据值索引和字母顺序对python字典进行排序

标签 python sorting dictionary

我正在尝试对 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),但这给出了一个错误,一个元组是收到而不是字符串。

有什么想法吗?我不能改变字典的构成方式,它必须保持原样。

最佳答案

你需要一个更复杂的键函数:

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

关于python - 根据值索引和字母顺序对python字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25004001/

相关文章:

python - Numpy 根据另一个数组的值分配一个数组值,并根据向量选择列

python - Pandas If Else 条件对多列

c - MexFile 导致 "Assertion detected"错误 - mexfiles 中的 memcpy 有问题吗?

iOS 根据浮点值排序数组

c++ - 查找 map C++ 未找到已添加到 map 中的键

python - 如何确保类型提示仍然适用于从集合继承 UserList 的类?

python - TensorFlow: "No gradients provided for any variable"和 partial_run

algorithm - 排序算法稳定有什么好处?

perl - "map"是循环吗?

python - 从 Pandas 数据框创建字典。在列上包含集合