Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to re-index a dictionary in python?

I originally has a dictionary like the following:

mydict = {int(i): 'values' for i in range(5)}
{0: 'values', 1: 'values', 2: 'values', 3: 'values', 4: 'values'} # output

then i removed two of the index:

del mydict[0]
del mydict[3]
{1: 'values', 2: 'values', 4: 'values'} # output

And now i would like to "reindex" the dictionary into something like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 {0: 'values', 1: 'values', 2: 'values'} # output

my real dictionary are much larger than this so it is not possible to do it manually..

>Solution :

You can use enumerate:

mydict = {1: 'a', 2: 'b', 4: 'd'}

mydict = dict(enumerate(mydict.values()))
print(mydict) # {0: 'a', 1: 'b', 2: 'd'}

Note that this is guaranteed only for python 3.7+. Before that, a dict is not required to preserve order.

If you do want to be safer, you can sort the items first:

mydict = {2: 'b', 1: 'a', 4: 'd'}

mydict = dict(enumerate(v for _, v in sorted(mydict.items())))
print(mydict) # {0: 'a', 1: 'b', 2: 'd'}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading