Answers for "python sort list of dict based on value"

5

python sort a dictionary by values

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}

sort_by_key = dict(sorted(x.items(),key=lambda item:item[0]))
sort_by_value = dict(sorted(x.items(), key=lambda item: item[1]))

print("sort_by_key:", sort_by_key)
print("sort_by_value:", sort_by_value)

# sort_by_key: {0: 0, 1: 2, 2: 1, 3: 4, 4: 3}
# sort_by_value: {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
Posted by: Guest on July-12-2021
0

python sort dictionary items by value

def sorted_dict_by_value(d: dict, reverse=False):
    # Sort the dictionary items by values
    marklist = sorted(d.items(), key=lambda x: x[1], reverse=reverse)
    return dict(marklist)
Posted by: Guest on September-01-2021

Code answers related to "python sort list of dict based on value"

Python Answers by Framework

Browse Popular Code Answers by Language