【问题标题】:sort list of dictionaries based on keys inside the list根据列表中的键对字典列表进行排序
【发布时间】:2018-04-16 21:04:38
【问题描述】:

如何根据dictionary 中的key 对其进行排序?

df1 = [('f', {'abe': 1}), ('f', {'tbeli': 1}), ('f', {'mos': 1}), ('f', {'esc': 1})]

我试过了

L1 = [year for (title, year) in (sorted(df1.items(), key=lambda t: t[0]))]

我想要

df1 = [('f', {'abe': 1}), ('f', {'esc': 1}), ('f', {'mos': 1}), ('f', {'tbeli': 1})]

谢谢

【问题讨论】:

  • 存储单项字典有什么用?

标签: python sorting dictionary


【解决方案1】:

您可以有一个单独的函数来获取可迭代项中的唯一项:

def only(iterable):
    x, = iterable
    return x

字典是键的可迭代对象:

>>> only({'abe': 1})
'abe'

>>> only({'tbeli': 1})
'tbeli'

因此您可以将其用于您的排序:

sorted(df1, key=lambda t: only(t[1]))

【讨论】:

    【解决方案2】:

    如果所有的字典都只有 1 个密钥/对,那么这应该可以工作。

    L1=sorted(df1, key=lambda t: list(t[1].keys())[0])

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-04
      相关资源
      最近更新 更多