silvercoder
silvercoder

Reputation: 149

If value from dictionary is in dataframe, return specific corresponding key

I am new to python and pandas so would love some guidance here! Given a dictionary and a DataFrame I am trying to extract the specific corresponding key if the value from the dictionary exists in the DataFrame.

For example:

Input:
    dict = {'Happy': [1, 2], 'Sad': [3, 4, 5]}
    
    people = {'Name': ['John','Tom','Helen'],'Status': [3,2,5]}
    df = pd.DataFrame(people, columns = ['Name', 'Status'])


Expected Output:
output_dict = {'John': 'Happy', 'Tom': 'Happy', 'Helen': 'Sad'}

Here is what I have tried so far:

    for key, value in dict.items():
        for val in value:
            for row in df.itertuples():
                if row.status == val:
                    return {df['Name']:key}

However for some reason my dict at the end is always returned as empty.

Upvotes: 1

Views: 313

Answers (1)

BENY
BENY

Reputation: 323246

Let us try modify your dict , then with replace or map

out = df.set_index('Name').Status.replace({z : x for x , y in d.items() for z in y } ).to_dict()
{'John': 'Sad', 'Tom': 'Happy', 'Helen': 'Sad'}

Upvotes: 2

Related Questions