python按照字典顺序输出字母_根据值索引和字母顺序对python字典进行排序

我正在尝试对python字典进行排序,并遇到了一些问题.字典采用以下格式:{UID:名称,类型}.

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

标签:dictionary,python,sorting

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值