I have a dictionary entries for the different users like below:
{'usr_1': '111', 'usr_2': '222','usr_22' : '3333',
'usr_8': '888','usr_11':'11111','usr_10':'10101'}
I want to sort this dictionary based on the key. The output should be
{'usr_1': '111', 'usr_2': '222','usr_8': '888',
'usr_10':'10101', 'usr_11':'11111','usr_22' : '3333'}
When I tried using the OrderedDict method it just returns changes the list to tuples and doesn't give me the sorted order I wanted.
dict1 = {'usr_1': '111', 'usr_2': '222','usr_22' : '3333',
'usr_8': '888','usr_11':'11111','usr_10':'10101'}
my_dict = OrderedDict(dict1)
print(my_dict)
Output
OrderedDict([('usr_1', '111'), ('usr_2', '222'), ('usr_22', '3333'),
('usr_8', '888'), ('usr_11', '11111'), ('usr_10', '10101')])
Can someone help me out?
CodePudding user response:
In order to sort strings that contain numbers numerically, you can right-justify them to a common maximum length:
dict(sorted(dict1.items(),key="{0[0]:>20}".format))
output:
{'usr_1': '111', 'usr_2': '222', 'usr_8': '888', 'usr_10': '10101',
'usr_11': '11111', 'usr_22': '3333'}
Note that this only works if the prefixing character is smaller than "0" (which "_" happens to be). If not, you would need to split the string or convert characters. (same goes if there are varying length non-digit prefixes)
CodePudding user response:
Use a lambda that splits on "_" as key:
out = dict(sorted(dct.items(), key=lambda x: int(x[0].split('_')[1])))
Output:
{'usr_1': '111',
'usr_2': '222',
'usr_8': '888',
'usr_10': '10101',
'usr_11': '11111',
'usr_22': '3333'}
CodePudding user response:
try
my_dict = OrderedDict(sorted(dict1.items()))
