python ternary operator with assignment

前端 未结 6 890
眼角桃花
眼角桃花 2021-01-22 23:01

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

         


        
6条回答
  •  温柔的废话
    2021-01-22 23:31

    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:

    • the value for the specified key if key is in dictionary.
    • None if the key is not found and value is not specified.
    • value if the key is not found and value is specified.

    Another option is to use defaultdict

    from collections import defaultdict
    
    d = defaultdict(dict)
    q = d[x]
    
    >>> q
    >>> {}
    

提交回复
热议问题