how to sort dict based on key values code example
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: sort dictionary
sorted(d.items(), key=lambda x: x[1])
sorted(d.items(), key=lambda x: x[1], reverse=True)
Example 3: 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)