如果键存在,则按键对python字典列表进行排序 [英] Sort python list of dictionaries by key if key exists

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

问题描述

我有一个这样的词典列表:

I have a list of dictionaries like this:

[{"foo" : "bar", "myKey" : "one"}, 
{"foo" : "bar", "myKey" : "two"}, 
{"foo" : "bar", "yourKey" : "three"}]

我想按字典中的键对它进行排序(如果存在).

I'd like to sort it by a key in the dictionary if it exists.

featured = sorted(filesToWrite, key=lambda k: k["myKey"])

如果"myKey"不存在,则此方法不起作用. 编辑:如果字典中不存在myKey,我希望它出现在列表的末尾.

This doesn't work if "myKey" doesn't exist. If myKey doesn't exist in the dictionary, I'd like it to appear at the end of the list.

我可以手动遍历列表,然后自己完成,但是我敢肯定,有一种Python方式可以完成我的目标,而无需做所有这些事情.

I could loop through the list manually and do it myself but I'm sure there is a pythonic way to accomplish my goal without doing all that.

推荐答案

查看

输出:

[{'foo': 'bar', 'myKey': 'one'}, {'foo': 'bar', 'myKey': 'two'}, {'yourKey': 'three', 'foo': 'bar'}]

魔术发生在钥匙上:

("myKey" in k, k.get("myKey", None)

哪个是两个项目的元组,例如:

Which is a two item tuple, like:

(True, "one")

在第一个元素为True/False的情况下,取决于密钥是否缺失(True在False之后,因此为not),第二个元素是所述密钥的值(如果存在).如果不是,请按None. (可以忽略该参数,但我将其包含在内是明确的)

Where the first element is True/False depending on whether or not the key is missing (True comes after False hence the not), and the second element is the value of said key, if it exists. If not, None. (that argument can be skipped, but I included it to be explicit)

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

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