I have a list of dictionaries and want each item to be sorted by a specific value.
Take into consideration the list:
[{\'name\':\'Homer\', \'age\':39},
Here is the alternative general solution - it sorts elements of a dict by keys and values.
The advantage of it - no need to specify keys, and it would still work if some keys are missing in some of dictionaries.
def sort_key_func(item):
""" Helper function used to sort list of dicts
:param item: dict
:return: sorted list of tuples (k, v)
"""
pairs = []
for k, v in item.items():
pairs.append((k, v))
return sorted(pairs)
sorted(A, key=sort_key_func)