如果键存在,则按键对python字典列表进行排序

编程入门 行业动态 更新时间:2024-10-19 11:54:18
本文介绍了如果键存在,则按键对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.

推荐答案

查看 dict.get :

featured = sorted(filesToWrite, key=lambda k: ("myKey" not in k, k.get("myKey", None)))

输出:

[{'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字典列表进行排序

本文发布于:2023-11-06 14:09:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563907.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   按键   列表   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!