how to sort dict by value
dict1 = {1: 1, 2: 9, 3: 4}
sorted_dict = {}
sorted_keys = sorted(dict1, key=dict1.get) # [1, 3, 2]
for w in sorted_keys:
sorted_dict[w] = dict1[w]
print(sorted_dict) # {1: 1, 3: 4, 2: 9}
how to sort dict by value
dict1 = {1: 1, 2: 9, 3: 4}
sorted_dict = {}
sorted_keys = sorted(dict1, key=dict1.get) # [1, 3, 2]
for w in sorted_keys:
sorted_dict[w] = dict1[w]
print(sorted_dict) # {1: 1, 3: 4, 2: 9}
sort a dictionary by value then key
d = {'apple': 2, 'banana': 3, 'almond':2 , 'beetroot': 3, 'peach': 4}
[v[0] for v in sorted(d.items(), key=lambda kv: (-kv[1], kv[0]))]
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us