python中字典按键或键值排序,Python中如何按键排序字典

Here is the dictionary looks like:

{'57481': 50, '57480': 89, '57483': 110, '57482': 18, '57485': 82, '57484': 40}

I would like to sort the dictionary in numerical order, the result should be:

{'57480': 89, '57481': 50, '57482': 18, '57483': 110, '57484': 40, '57485': 82}

I tried sorted(self.docs_info.items) but it doesn't work.

解决方案

If you only need to sort by key, you're 95% there already. Assuming your dictionary seems to be called docs_info:

for key, value in sorted(docs_info.items()): # Note the () after items!

print(key, value)

Since dictionary keys are always unique, calling sorted on docs_info.items() (which is a sequence of tuples) is equivalent to sorting only by the keys.

Do bear in mind that strings containing numbers sort unintuitively! e.g. "11" is "smaller" than "2". If you need them sorted numerically, I recommend making the keys int instead of str; e.g.

int_docs_info = {int(k) : v for k, v in docss_info.items()}

This of course just changes the order in which you access the dictionary elements, which is usually sufficient (since if you're not accessing it, what does it matter if it's sorted?). If for some reason you need the dict itself to be "sorted", then you'll have to use collections.OrderedDict, which remembers the order in which items were inserted into it. So you could first sort your dictionary (as above) and then create an OrderedDict from the sorted (key, value) pairs:

sorted_docs_info = collections.OrderedDict(sorted(docs_info.items()))

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值