根据列表中的键对字典列表进行排序 [英] sort list of dictionaries based on keys inside the list

查看:423
本文介绍了根据列表中的键对字典列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I sort this based on the key in dictionary?

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

谢谢

推荐答案

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

You could have a separate function to get the only item in an iterable:

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

数字是键的可迭代项:

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

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

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

so you can use it for your sort:

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

这篇关于根据列表中的键对字典列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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