I am new to python. I\'m trying to write this
if x not in d:
d[x] = {}
q = d[x]
in a more compact way using the ternary operator
That's what setdefault() is for:
q = d.setdefault(x, {})
It does exactly what you want:
d[x]
if x
is a key in d
{}
to d[x]
if x
is not yet a key and return thatIn Python, assignments cannot occur in expressions, therefore you can't write code like a = (b = c)
.
You're looking for setdefault:
q = d.setdefault(x, {})
Alternative, use a defaultdict.
The conditional operator in Python is used for expressions only, but assignments are statements. You can use
q = d.setdefault(x, {})
to get the desired effect in this case. See also the documentation of dict.setdefault().
The reason that else (d[x] = {})
is a syntax error is that in Python, assignment is a statement. But the conditional operator expects expressions, and while every expression can be a statement, not every statement is an expression.
For those interested in the ternary operator (also called a conditional expression), here is a way to use it to accomplish half of the original goal:
q = d[x] if x in d else {}
The conditional expression, of the form x if C else y
, will evaluate and return the value of either x
or y
depending on the condition C
. The result will then be assigned to q
.
You can also use Python's dictionary get() method
q = d.get(x, {})
Explanation:
The get() method returns the value for the specified key if key is in a dictionary.
The syntax of get() is:
dict.get(key[, value])
get() Parameters
The get() method takes maximum of two parameters:
key - key to be searched in the dictionary
value (optional) - Value to be returned if the key is not found. The default value is None.
Return Value from get()
The get() method returns:
Another option is to use defaultdict
from collections import defaultdict
d = defaultdict(dict)
q = d[x]
>>> q
>>> {}