加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python:在密钥上排序dicts的字典

发布时间:2020-12-20 12:28:06 所属栏目:Python 来源:网络整理
导读:像这样的数据结构. { 'ford': {'count': 3},'mazda': {'count': 0},'toyota': {'count': 1} } 在顶级字典值中对count值进行排序的最佳方法是什么? 解决方法 d = {'ford': {'count': 3},'toyota': {'count': 1}} sorted(d.items(),key=lambda (k,v): v['coun
像这样的数据结构.

{
  'ford': {'count': 3},'mazda': {'count': 0},'toyota': {'count': 1}
 }

在顶级字典值中对count值进行排序的最佳方法是什么?

解决方法

d = {'ford': {'count': 3},'toyota': {'count': 1}}

>>> sorted(d.items(),key=lambda (k,v): v['count'])
[('mazda',{'count': 0}),('toyota',{'count': 1}),('ford',{'count': 3})]

要将结果保存为字典,可以使用collections.OrderedDict

>>> from collections import OrderedDict
>>> ordered = OrderedDict(sorted(d.items(),v): v['count']))
>>> ordered
OrderedDict([('mazda',{'count': 3})])
>>> ordered.keys()          # this is guaranteed to come back in the sorted order
['mazda','toyota','ford']
>>> ordered['mazda']        # still a dictionary
{'count': 0}

版本问题:

>在Python 2.x上,您可以使用d.iteritems()而不是d.items()来提高内存效率> collections.OrderedDict仅适用于Python 2.7和Python 3.2(及更高版本)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读