如果键存在,则按键对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.