Home > Software engineering >  How to reference a dictionary key based on the function object
How to reference a dictionary key based on the function object

Time:10-21

I have a function object in a dictionary called parsing_map how do I reference the dictionary key based on what the function object is called

import pandas as pd
import numpy as np

data= [["john",np.nan,np.nan,"English"]]
df= pd.DataFrame(data,columns=['firstName', 'lastName', 'state', 'Communication_Language__c'])

def lang(col, df):
    col.replace(lang, inplace=True) 
    col = col.str.upper()
    return df

parsing_map={
"Communication_Language__c": lang
}

I would like to call all keys in the parsing_map dictionary that have the function name "lang" (only one for simplicity) after referencing the dictionary key name I wasnt to use it as a local variable to run an operation

I know col is not correct but I would like to replace anything in the df[Communication_langauge_c] with the abbreviated value

lang= {"English":"ENG", "French":"FR"}

def lang(col, df):
    col.replace(lang, inplace=True) 
    col = col.str.upper()
    return df

desired output: change English to ENG in the dataframe

How do I reference the dictionary function to find all dictionary keys with the assigned function?

CodePudding user response:

I'm a little bit confused, but if you just want to get all the dictionary keys that have a certain value, you can do smth. like this:

[col for col,func in d.items() if func == lang]

This would output you a list of all dictionary keys that have the the function lang as dictionary key. Does this help you?

if you want to use the keys you found as column names in a dataframe and apply a function to said columns you can do the following:

def column_func(x):
   ### do smth
   x.replace("abc", "def")
   return x

key_list = [col for col, func in d.items() if func == 1]

for key in key_list:
    df[key].apply(column_func)

CodePudding user response:

You can use pd.Series.map like so:

lang = {"English": "ENG", "French": "FR"}

df['Communication_Language__c'] = df['Communication_Language__c'].map(lang)
  • Related