在Python中按值排序嵌套字典,并将其余值排序为另一个值 [英] Sort nested dictionary by value, and remainder by another value, in Python

查看:209
本文介绍了在Python中按值排序嵌套字典,并将其余值排序为另一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  {'KEY1':{'name':'google','date' 20100701,'downloads':0},
'KEY2':{'name':'chrome','date':20071010,'downloads':0},
'KEY3':{'name ':'python','date':20100710,'downloads':100}}

d喜欢首先按下载排序的字典,然后按日期排序的所有项目都没有下载。显然一个字典不能排序,我只需要一个排序列表的键,我可以迭代。

  ['KEY3','KEY1','KEY2'] 
pre>

我可以使用排序的任何一个值排序列表,但是如何使用第二个值排序?

解决方案

使用键 ()。它允许您指定一个函数,给定正在排序的实际项目返回应该排序的值。如果这个值是一个元组,那么它将像元组排序 - 第一个值,然后是第二个值。

 排序(your_list,key = lambda x:(your_dict [x] ['downloads'],your_dict [x] ['date'])


Consider this dictionary format.

{'KEY1':{'name':'google','date':20100701,'downloads':0},
 'KEY2':{'name':'chrome','date':20071010,'downloads':0},
 'KEY3':{'name':'python','date':20100710,'downloads':100}}

I'd like the dictionary sorted by downloads first, and then all items with no downloads sorted by date. Obviously a dictionary cannot be sorted, I just need a sorted listed of keys I can iterate over.

['KEY3','KEY1','KEY2']

I can already sort the list by either value using sorted, but how do I sort by second value too?

解决方案

Use the key argument for sorted(). It lets you specify a function that, given the actual item being sorted, returns a value that should be sorted by. If this value is a tuple, then it sorts like tuples sort - by the first value, and then by the second value.

sorted(your_list, key=lambda x: (your_dict[x]['downloads'], your_dict[x]['date']))

这篇关于在Python中按值排序嵌套字典,并将其余值排序为另一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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