Jacob69
0
Q:

sorting a dictionary in python

sortedDictionary = sorted(mydictionary.keys())
3
#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
1
d = {2: 3, 1: 89, 4: 5, 3: 0}
od = sorted(d.items())
print(od)
1
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
{k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
6

 print(sorted(key_value.items(), key = lambda kv:(kv[1], kv[0])))     

2
In [1]: import collections

In [2]: d = {2:3, 1:89, 4:5, 3:0}

In [3]: od = collections.OrderedDict(sorted(d.items()))

In [4]: od
Out[4]: OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])
1

New to Communities?

Join the community