Enumerate numpy array differently?

Question:

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()}
Asked By: user13744439

||

Answers:

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()))
Answered By: chrslg

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))
Answered By: R. Baraiya
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.