0

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)
4
  • 1
    result = exampleFunction(*my_dict.values()) Commented Mar 7, 2022 at 21:42
  • i would like an explanation please Commented Mar 7, 2022 at 21:43
  • 2
    my_dict has 2 "name" keys, the first will be overridden by the second. Commented Mar 7, 2022 at 21:44
  • messed up my copy paste. its an id Commented Mar 7, 2022 at 21:49

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.