Example 1: 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)
Example 2: sorting a dictionary in python
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}
Example 3: sorting values in dictionary in python
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))
Example 4: sort dict of dicts by key
channels = {
'24': {'type': 'plain', 'table_name': 'channel.items.AuctionChannel'},
'26': {'type': 'plain', 'table_name': 'channel.gm.DeleteAvatarChannel'},
'27': {'type': 'plain', 'table_name': 'channel.gm.AvatarMoneyChannel'},
'20': {'type': 'plain', 'table_name': 'channel.gm.AvatarMoneyAssertChannel'},
'21': {'type': 'plain', 'table_name': 'channel.gm.AvatarKillMobComplexChannel'},
'22': {'type': 'plain', 'table_name': 'channel.gm.DistributionMarkChannel'},
'23': {'type': 'plain', 'table_name': 'channel.gm.MailChannel'}
}
channels = collection.OrderedDict(sorted(channels.items(), key=lambda item: item[0]))
for key,value in channels.items():
print(key, ':', value)