How to assign multiple column in one go with dictionary values?

Question:

I have a pandas dataframe and a function that returns a dictionary. I want to assign the result of the function to multiple columns. But the problem is, the function returns a dictionary that I want to save only the values to columns. I can do this by sending only the values from the function. However, I want to solve if from the recipient side.

Example code:

import pandas as pd

data = {
  "col1": [420, 380, 390],
  "col2": [50, 40, 45]
}

#load data into a DataFrame object:
df = pd.DataFrame(data)

The following function returns a dictionary. ( Can solve by returning return fun_dict.values(), but I want to send the dictionary and solve it from the calling side)

def fun_function(my_input):
    fun_dict = {}
    
    fun_dict["num1"] = str(my_input)[0]
    fun_dict["num2"]  = str(my_input)[1]
    
    return fun_dict

Driving side/recipient side:

df["first_num_col"], df["last_num_col"] = zip(*df["col2"].map(fun_function))

With this code, I only get the key values, under each column. Any help/suggestion is appreciated. Thank you.

Asked By: Droid-Bird

||

Answers:

The only way I can think of is to do d.values() in the client side:

df["first_num_col"], df["last_num_col"] = zip(*[d.values() for d in df["col2"].map(fun_function)])
Answered By: TYZ