我有一个列表,当我循环访问我的数据时,我正在附加一个字典...我希望按其中一个字典键排序.
例如:
data = "data from database" list = [] for x in data: dict = {'title':title, 'date': x.created_on} list.append(dict)
我想按"date"的值按相反的顺序对列表进行排序
你可以这样做:
list.sort(key=lambda item:item['date'], reverse=True)
from operator import itemgetter your_list.sort(key=itemgetter('date'), reverse=True)
不要使用list
,dict
作为变量名,它们是Python中的内置名称.它使您的代码难以阅读.
您可能需要根据上下文替换字典tuple
或者使用collections.namedtuple
类似自定义类的类替换字典
from collections import namedtuple from operator import itemgetter Row = namedtuple('Row', 'title date') rows = [Row(row.title, row.created_on) for row in data] rows.sort(key=itemgetter(1), reverse=True)
例:
>>> lst = [Row('a', 1), Row('b', 2)] >>> lst.sort(key=itemgetter(1), reverse=True) >>> lst [Row(title='b', date=2), Row(title='a', date=1)]
要么
>>> from operator import attrgetter >>> lst = [Row('a', 1), Row('b', 2)] >>> lst.sort(key=attrgetter('date'), reverse=True) >>> lst [Row(title='b', date=2), Row(title='a', date=1)]
下面是如何namedtuple
看起来里面:
>>> Row = namedtuple('Row', 'title date', verbose=True) class Row(tuple): 'Row(title, date)' __slots__ = () _fields = ('title', 'date') def __new__(cls, title, date): return tuple.__new__(cls, (title, date)) @classmethod def _make(cls, iterable, new=tuple.__new__, len=len): 'Make a new Row object from a sequence or iterable' result = new(cls, iterable) if len(result) != 2: raise TypeError('Expected 2 arguments, got %d' % len(result)) return result def __repr__(self): return 'Row(title=%r, date=%r)' % self def _asdict(t): 'Return a new dict which maps field names to their values' return {'title': t[0], 'date': t[1]} def _replace(self, **kwds): 'Return a new Row object replacing specified fields with new values' result = self._make(map(kwds.pop, ('title', 'date'), self)) if kwds: raise ValueError('Got unexpected field names: %r' % kwds.keys()) return result def __getnewargs__(self): return tuple(self) title = property(itemgetter(0)) date = property(itemgetter(1))