Ganga
Ganga

Reputation: 305

Sort a dictionary in python based on keys in ascending order

I have a dictionary :

I am using inbuilt function to sort dictionary dict(sorted(d.items()))

I want my output to be like :

{'0':'0','1':'0','2':'0','3':'1245','4':.......}

but now the order of keys is 0,1,10,100

I want to have 1,2,3,4 ...

d={'113': '5', '114': '305', '115': '50', '116': '0', '117': '0', '118': '0', '119': '0', '12': '1245', '120': '0', '121': '0', '122': '10', '123': '10', '124': '0', '125': '0', '126': '0', '127': '0', '128': '0', '129': '610,'0': '0', '1': '0', '10': '0', '100': '0', '101': '0', '102': '0', '103': '0', '108': '0', '109': '194', '11': '0', '110': '340', '111': '0', '112': '10', '', '13': '0', '130': '20','104': '120', '105': '105', '106': '0', '107': '0'}

print(dict(sorted(d.items())))

The output looks like this

{'0': '0', '1': '0', '10': '0', '100': '0', '101': '0', '102': '0', '103': '0', '104': '120', '105': '105', '106': '0', '107': '0', '108': '0', '109': '194', '11': '0', '110': '340', '111': '0', '112': '10', '113': '5', '114': '305', '115': '50', '116': '0', '117': '0', '118': '0', '119': '0', '12': '1245', '120': '0', '121': '0', '122': '10', '123': '10', '124': '0', '125': '0', '126': '0', '127': '0', '128': '0', '129': '610', '13': '0', '130': '20'}

Please help me with the right approach to sort it in this way .

Upvotes: 0

Views: 150

Answers (3)

Amandeep Singh
Amandeep Singh

Reputation: 521

You can use OrderedDict

from collections import OrderedDict
d = OrderedDict(d)

Upvotes: 0

Chrismon Chin
Chrismon Chin

Reputation: 429

If you want the items sorted, you cannot keep it in a dictionary afterwards. A dictionary does not preserve order.

This will give you the output as a sorted list:

sorted(d.items(), key=lambda x: int(x[0]))

Upvotes: 1

Abercrombie
Abercrombie

Reputation: 1086

Since you wanted zero-based indexing for your sorted dictionary, the following solution should work for your use case.

a = dict(sorted(d.items()))
res = {}
ctr=0
for i in a.keys():
  res[ctr] = a[i]
  ctr+=1

print(res)

Upvotes: 0

Related Questions