Sort a list of Dictionaries by list of strings

Viewed 92

How can i sort a list of dictionaries using a predetermined list of strings

Ordered List of Strings

["Apple", "Watermellon", "Orange", "Grape"]

Collected Dictionary Data

{
    "Grape": {"value": 3},
    "Watermellon": {"value": 5},
    "Orange": {"value": 8},
    "Apple": {"value": 1}
}

Desired order of dictionary...assuming I'll have to convert it to a list of some sort in order to maintain order.

{
    "Apple": {"value": 1},
    "Watermellon": {"value": 5},
    "Orange": {"value": 8},
    "Grape": {"value": 3},
}
2 Answers

If you don't want to rely on the insertion order of dictionaries and python versions, you can turn it into a sorted list, for example:

order = ["Apple", "Watermellon", "Orange", "Grape"]

data = {
    "Grape": {"value": 3},
    "Watermellon": {"value": 5},
    "Orange": {"value": 8},
    "Apple": {"value": 1}
}

ordered_data = sorted(data.items(), key=lambda item: order.index(item[0]))
print(ordered_data)

>>> [('Apple', {'value': 1}), ('Watermellon', {'value': 5}), ('Orange', {'value': 8}), ('Grape', {'value': 3})]

Since Python3.6 (guaranteed in Python3.7), dicts are ordered by insertion order.

So a simple comprehension dict do the trick:

print({key: d.get(key, {"value": 0}) for key in l})

I took the liberty to default value in case your key is not present.

For versions before 3.6 you can use OrderedDict

Source: Python doc

Performing list(d) on a dictionary returns a list of all the keys used in the dictionary, in insertion order

Related