How to pass my variable as a string into function

I have wrote lines of code to convert items of a pandas dataframe column to a dict with appropriate values. The code looks like this:

states = df.STATE.unique()
states_values = [i for i in range(0,len(states))]
state_dict = {states[i]: states_values[i] for i in range(len(states))}

But I have many columns to convert so I tried using a function and wrote a function like this

def make_dict(dataframe,column_name):
    keys = dataframe.column_name.unique()
    values = [i for i in range(0,len(keys))]
    dict = {keys[i]: values[i] for i in range(len(keys))}
    return dict

But When I tried

city_dict = make_dict(df,'CITY')

Where CITY is my column name, it throws an error

AttributeError: 'DataFrame' object has no attribute 'column_name'

I have tried setting a variable and did it but same error.

tried with df['CITY'] over df.CITY but still doesn’t work out.
Please let me know what am I missing.

>Solution :

You can use getattr() to fetch arbitrary attributes.

keys = getattr(dataframe, column_name).unique()

Leave a Reply