python – Assign a value to a dictionary variable that is optional


I have a function where one of the parameters is a dictionary, but it's optional.

I need to assign a value in this dictionary, but take into account the case where this parameter is not filled.

The following solution uses two lines for this:

def uma_funcao(um_dict=None):
    um_dict = um_dict or {}
    um_dict['uma_chave'] = True

I believe there is a more iconic way of doing it, in a single line. It's possible?


No, I believe that this form you presented is already minimal. I can't talk about Python 3 as I have no experience.

(Answers to the negative are complicated, but I have no supporting evidence, except the absence of evidence to the contrary…)

Update: as 3 people have already posted the same incorrect answer, I will point it out here to avoid future identical answers.

>>> def uma_funcao(um_dict={}):
...   um_dict['uma_chave'] = True
...   return um_dict
>>> x = uma_funcao()
>>> x['teste'] = True
>>> y = uma_funcao()
>>> y
{'uma_chave': True, 'teste': True}

As you can see, you shouldn't use a mutable value as a default parameter of a function. The expression {} creates an object before being used as a parameter, so every call to uma_funcao without passing parameters will use the same dict . As this is rarely the desired behavior, there is no option but to use None followed by a test, as in the original question code.

Another way that occurred to me, very common in languages ​​like C, was to unite the attribution with the use in a single expression:

(um_dict = um_dict or {})['uma_chave'] = True

However this is not allowed by Python syntax (2 at least; if anything like this has been added in future versions, it is not to my knowledge).

Scroll to Top