Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Function – Dictionary as Input – Return Error – Interesting Behavior

Good day, brilliant Stack Overflow Community. I noticed an interesting behavior regarding Python function when input as a dictionary.

When we use the empty list as a default argument, we can return that list while appending some value.

def func_list(value,input=[]):
    return input.append(value)

I would expect the same thing to apply when empty dictionary as an argument. such as:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def func_dict(value,input={}):
    return input[value] = value

However, Python will raise a Syntax Error, and I can only do something like:

def func_dict(value,input={}):
    input[value] = value
    return input

I am wondering why? Thank you so much!

PS. Please feel free to modify the question, and apologize if my expression of the question is not clear enough!

>Solution :

The key difference is that input.append(value) is an expression and input[value] = value is not (it is just a statement). The return statement can only take an expression as a parameter (or no parameters to return None).

You CAN do this:

def func_dict(value,input={}):
    return input.update({ value: value }) or input

How this works is that dict.update() returns None so we return the (now updated) input instead. I know it’s ugly but can’t think of a better one.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading