[英]Sort data based on key of a list of multiple dictionaries
I have a list like this 我有这样的清单
li = [
{1: {'amount': 255, 'date': '25-02-2017'}},
{2: {'amount': 25, 'date': '2-02-2017'}},
{3: {'amount': 38, 'date': '20-02-2017'}},
]
I am trying to sort the data in ascending and descending order based on 'amount'
. 我试图基于
'amount'
来对数据进行升序和降序排序。
I tried the following but am unable to get the result I want: 我尝试了以下操作,但无法获得想要的结果:
import operator
li.sort(key=operator.itemgetter('amount'))
and 和
from operator import itemgetter
newlist = sorted(li, key=itemgetter('amount'))
Both raise an exception, KeyError: 'amount'
. 两者都引发异常
KeyError: 'amount'
。
You have a list of dictionaries with a single key, whose value is another dictionary. 您有一个带有单个键的字典列表,其值是另一个字典。 It is that nested dictionary that has the key
'amount'
. 那个嵌套字典具有键
'amount'
。
You'd have to reach in and get that single value: 您必须达到并获得该单一价值:
newlist = sorted(li, key=lambda d: d.values()[0]['amount'])
This only works in Python 2, where d.values()
is a list. 这仅在Python 2中有效,其中
d.values()
是列表。 In Python 3 you'd have to use next(iter(d.values())['amount']
instead. 在Python 3中,您必须使用
next(iter(d.values())['amount']
。
You'd be much better of not producing the nested structure at all . 你一定会觉得很没有产生嵌套结构在所有的更好。 Move those numbered keys into another key-value pair perhaps:
将那些编号的键移动到另一个键值对中:
li = [
{'id': 1', amount': 255, 'date': '25-02-2017'},
{'id': 2, 'amount': 25, 'date': '2-02-2017'},
{'id': 3, 'amount': 38, 'date': '20-02-2017'},
]
at which point your original attempt would work. 在这一点上,您最初的尝试会奏效。 You can transform your current data structure with
[dict(id=d.keys()[0], **d.values()[0]) for d in li]
but it'd be better to fix the code that produced the list. 您可以使用
[dict(id=d.keys()[0], **d.values()[0]) for d in li]
转换当前数据结构,但最好修复产生的代码名单。
Try the following code which uses lambdas, 请尝试以下使用lambda的代码,
li=[{1:{'amount':255,'date':'25-02-2017'}},{2:{'amount':25,'date':'2-02-2017'}},{3:{'amount':38,'date':'20-02-2017'}}]
print(li)
li.sort(key=lambda x:list(x.values())[0]['amount']) # ascending
print(li)
li.sort(key=lambda x:list(x.values())[0]['amount'],reverse=True) # descending
print(li)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.