Home > Software engineering >  Enumerate numpy array differently?
Enumerate numpy array differently?

Time:10-12

import numpy as np
from datetime import date

arr= np.arange(date(2020, 1, 1), date(2021, 1, 1)).astype(str)
dict_required = dict(enumerate(arr))

above is the stuff, I am doing. This is the dictionary I get:

{0: '2020-01-01',
 1: '2020-01-02',
 2: '2020-01-03',
 3: '2020-01-04',

I want it other way. The key above should be value and value should be key. I am able to invert it like below. But, is it possible to do the same while enumerating?

inv_map = {v: k for k, v in dict_required.items()}

CodePudding user response:

Just to add another solution to the one given in comments ({v:k for k,v in enumerate(arr), which is the most "pythonesque", and has the advantage, in your case to avoid builing the 1st dictionary)

You can reverse a dictionary that way:

dict(map(reversed, mydic.items()))

CodePudding user response:

you can try following way, where we creating new dictionary by putting old dict values on keys positions and keys to values positions.

Code:

dict(zip(dict_required.values(), dict_required.keys()))

Or

dict(zip(dict_required.values(),dict_required))
  • Related