Python:排序这个字典(dict in dict) [英] Python: sort this dictionary (dict in dict)

查看:99
本文介绍了Python:排序这个字典(dict in dict)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

b':{'k':''''''''''''''''' 'sort by k'}}

想要排序这个字典,按照降序排列,在python中。



有点棘手,请帮忙。

解决方案

dict s无序。所以没有办法直接排序,但如果你是
愿意将 dict 转换成(key,value)组列表,那么你可以这样做:

 在[9]中:d 
输出[9]:{'a':{' b':'无论','k':1},'b':{'b':'sort by k','k':2}}

在[15] (d.items(),key = lambda x:x [1] ['k'],reverse = True)
输出[15]:[('b',{'b' ','k':2}),('a',{'b':'whatever','k':1})]

优秀的迷你版本解释了使用参数。


d = { 'a':{'k':1, 'b':'whatever'},  'b':{'k':2, 'b':'sort by k'} }

Want to sort this dictionary by k as descending order, in python.

Little tricky, please help.

解决方案

dicts are unordered. So there is no way to sort them directly, but if you are willing to convert the dict into a list of (key,value)-tuples, then you could do this:

In [9]: d
Out[9]: {'a': {'b': 'whatever', 'k': 1}, 'b': {'b': 'sort by k', 'k': 2}}

In [15]: sorted(d.items(),key=lambda x: x[1]['k'],reverse=True)
Out[15]: [('b', {'b': 'sort by k', 'k': 2}), ('a', {'b': 'whatever', 'k': 1})]

This excellent mini-howto explains the use of the key parameter.

这篇关于Python:排序这个字典(dict in dict)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆