DekGenius.com
PYTHON
how can I sort a dictionary in python according to its values?
s = {1: 1, 7: 2, 4: 2, 3: 1, 8: 1}
k = dict(sorted(s.items(),key=lambda x:x[0],reverse = True))
print(k)
dictionary sort python
d={
3: 4,
1: 1,
0: 0,
4: 3,
2: 1
}
y=dict(sorted(d.items(), key=lambda item: item[1]))
print(y) # {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
sort dictionary python
l = {1: 40, 2: 60, 3: 50, 4: 30, 5: 20}
d1 = dict(sorted(l.items(),key=lambda x:x[1],reverse=True))
print(d1) #output : {2: 60, 3: 50, 1: 40, 4: 30, 5: 20}
d2 = dict(sorted(l.items(),key=lambda x:x[1],reverse=False))
print(d2) #output : {5: 20, 4: 30, 1: 40, 3: 50, 2: 60}
sort dictionary
#for dictionary d
sorted(d.items(), key=lambda x: x[1]) #for inceasing order
sorted(d.items(), key=lambda x: x[1], reverse=True) # for decreasing order
#it will return list of key value pair tuples
sort the dictionary in python
d = {2: 3, 1: 89, 4: 5, 3: 0}
od = sorted(d.items())
print(od)
python dictionary sort
# empty dictionary
dictionary = {}
# lists
list_1 = [1, 2, 3, 4, 5]
list_2 = ["e", "d", "c", "b", "a"]
# populate a dictionary.
for key, value in zip(list_1, list_2):
dictionary[key] = value
# original
print(f"Original dictionary: {dictionary}")
# Sort dictionary based on value
dictionary_sorted = dict(sorted(dictionary.items(), key=lambda value: value[1]))
print(f"Sort dictionary by value: {dictionary_sorted}")
# Sort dictionary based on key
dictionary_sorted = dict(sorted(dictionary.items(), key=lambda key: key[0]))
print(f"Sort dictionary by key: {dictionary_sorted}")
python sort the values in a dictionary
from operator import itemgetter
new_dict = sorted(data.items(), key=itemgetter(1))
Sorting a List of Dictionaries
csv_mapping_list = [
{ "Name": "Jeremy", "Age": 25, "Favorite Color": "Blue" },
{ "Name": "Ally", "Age": 41, "Favorite Color": "Magenta" },
{ "Name": "Jasmine", "Age": 29, "Favorite Color": "Aqua" }
]
# Custom sorting
size = len(csv_mapping_list)
for i in range(size):
min_index = i
for j in range(i + 1, size):
if csv_mapping_list[min_index]["Age"] > csv_mapping_list[j]["Age"]:
min_index = j
csv_mapping_list[i], csv_mapping_list[min_index] = csv_mapping_list[min_index], csv_mapping_list[i]
# List sorting function
csv_mapping_list.sort(key=lambda item: item.get("Age"))
# List sorting using itemgetter
from operator import itemgetter
f = itemgetter('Name')
csv_mapping_list.sort(key=f)
# Iterable sorted function
csv_mapping_list = sorted(csv_mapping_list, key=lambda item: item.get("Age"))
sorting values in dictionary in python
#instead of using python inbuilt function we can it compute directly.
#here iam sorting the values in descending order..
d = {1: 1, 7: 2, 4: 2, 3: 1, 8: 1}
s=[]
for i in d.items():
s.append(i)
for i in range(0,len(s)):
for j in range(i+1,len(s)):
if s[i][1]<s[j][1]:
s[i],s[j]=s[j],s[i]
print(dict(s))
sorting dictionary in python
Sorting a dictionary in python
© 2022 Copyright:
DekGenius.com