'How do I sort a list of dictionaries by a value of the list?

aa = ['a', 'b', 'c', 'd']
bb = [{'b':1, 'c':0, 'd':2, 'a':5}, {'b':5, 'c':6, 'd':1, 'a':2}]

I want to arrange the dicts in bb list by aa list.

bb = [{'a':5, 'b':1, 'c':0, 'd':2}, {'a':2, 'b':5, 'c':6, 'd':1}]


Solution 1:[1]

You can use list- and dict-comprehensions:

aa = ['a', 'b', 'c', 'd']
bb = [{'b':1, 'c':0, 'd':2, 'a':5}, {'b':5, 'c':6, 'd':1, 'a':2}]

output = [{k: dct[k] for k in aa} for dct in bb]
print(output)
# [{'a': 5, 'b': 1, 'c': 0, 'd': 2}, {'a': 2, 'b': 5, 'c': 6, 'd': 1}]

This "sorting" is guaranteed since python 3.7.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1