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
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
>>> {}