How to re-index a dictionary in python?

Question:

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:

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

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

Asked By: Math Avengers

||

Answers:

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'}
Answered By: j1-lee

You can do this in another way using zip (ref) at once. If:

dict_ = {1: 'values', 2: 'values', 4: 'values'}

d = dict(zip(range(3), list(dict_.values())))
# {0: 'values', 1: 'values', 2: 'values'}

Here, range(3) is the target list that will be as new keys.

Answered By: Ali_Sh
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.