Sort python list of dictionaries by key if key exists

python, sorting

Solution

Check out `dict.get`:

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

Output:

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

The magic happens in the key:

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

Which is a two item tuple, like:

(True, "one")

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)

Problem

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"]) ``` This doesn't work if `"myKey"` doesn't exist. EDIT: If `myKey` doesn't exist in the dictionary, I'd like it to appear at the end of the list. 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.

Original source

Related problems