Home > Back-end >  How to re-index a dictionary in python?
How to re-index a dictionary in python?

Time:08-27

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..

CodePudding user response:

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'}

CodePudding user response:

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.

  • Related