Home > database >  Unpack dictionary values into function arguments
Unpack dictionary values into function arguments

Time:03-08

I would like to unpack dictionary values and pass them into function arguments. I have a 1D dictionary that might contain strings, integers and floats or all together as values.

In the example code Im using the latest case. The dictionary contains integers, floats and strings as values.

Example Dictionary

my_dict = {'name': 'String VaLue', 'id': 1, 'price': 10.5 }

Example function:

def exampleFunction(valueA, valueB, ValueC):
    # Do something

I have tried using the values() function to extract the values but I get a float value error.

Desired result:

my_dict = {'name': 'String VaLue', 'id': 1, 'price': 10.5 }

# Dictionary value extraction

# Passing extracted values as function arguments
 result = exampleFunction('String VaLue', 1, 10.5)

CodePudding user response:

mydict.values() is a sequence of all the values in the dictionary mydict.

In the context of a function call, *foo means "pass each item in sequence foo as a separate argument".

Putting these two concepts together, we get:

exampleFunction(*my_dict.values())

If you're getting a float error, that likely means that the float value is being passed as (say) the second item when you expected it to be the third.

  • Related