Home > OS >  What is the best way to create a dictionary using unique column values, and the corresponding range?
What is the best way to create a dictionary using unique column values, and the corresponding range?

Time:10-01

I am trying to create a dictionary with keys being the alphabetized, unique values of a column, and the values being the value of range.

So for example, If i have a column called "States" that we expect to have 50 unique values, there would be 50 keys, each containing a state. I would want the corresponding key to be 1 for the first key, and 50 for the last key.

The dictionary would look like this: {'AL':1, 'AK':2, .... 'WV':49, 'WY':50}

Ive tried something as follows -

mapper = {df.Statee.unique().tolist()[i]:i for i in range(1, len(df.State.unique().tolist() 1))}

but that doesn't work.

CodePudding user response:

Something like this strikes me as most readable:

uniqs = df.State.unique()
mapper = {k:v 1 for v, k in enumerate(uniqs)}
  • Related