简体   繁体   English

在 python 中按日期对字典值列表进行排序

[英]sorting a list of dictionary values by date in python

I have a list and I am appending a dictionary to it as I loop through my data...and I would like to sort by one of the dictionary keys.我有一个列表,当我遍历我的数据时,我正在向它附加一个字典……我想按字典键之一进行排序。

ex:前任:

data = "data from database"
list = []
for x in data:
     dict = {'title':title, 'date': x.created_on}
     list.append(dict)

I want to sort the list in reverse order by value of 'date'我想按“日期”的值以相反的顺序对列表进行排序

You can do it this way:你可以这样做:

list.sort(key=lambda item:item['date'], reverse=True)
from operator import itemgetter

your_list.sort(key=itemgetter('date'), reverse=True)

Related notes相关说明

  • don't use list , dict as variable names, they are builtin names in Python.不要使用listdict作为变量名,它们是 Python 中的内置名称。 It makes your code hard to read.它使您的代码难以阅读。

  • you might need to replace dictionary by tuple or collections.namedtuple or custom struct-like class depending on the context您可能需要用tuplecollections.namedtuple或自定义结构类 class 替换字典,具体取决于上下文

    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)

Example:例子:

>>> 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)]

Or或者

>>> 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)]

Here's how namedtuple looks inside:这是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))

I actually had this almost exact question yesterday and solved it using search .实际上,我昨天有这个几乎完全相同的问题,并使用 search 解决了它 The best answer applied to your question is this:适用于您的问题的最佳答案是:

from operator import itemgetter
list.sort(key=itemgetter('date'), reverse=True)

Sort the data (or a copy of the data) directly and build the list of dicts afterwards.直接对数据(或数据的副本)进行排序,然后构建字典列表。 Sort using the function sorted with an appropiate key function (operator.attrgetter probably)使用 function 排序,使用适当的键 function 排序(可能是 operator.attrgetter)

If you're into the whole brevity thing:如果你对整个简洁的事情感兴趣:

data = "data from database"
sorted_data = sorted(
    [{'title': x.title, 'date': x.created_on} for x in data], 
    key=operator.itemgetter('date'),
    reverse=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM