如果键存在,则按键对python字典列表进行排序 [英] Sort python list of dictionaries by key if key exists
本文介绍了如果键存在,则按键对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.
推荐答案
查看全文