python ternary operator with assignment

前端 未结 6 882
眼角桃花
眼角桃花 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:09

    That's what setdefault() is for:

    q = d.setdefault(x, {})
    

    It does exactly what you want:

    • Return d[x] if x is a key in d
    • Assign {} to d[x] if x is not yet a key and return that
    0 讨论(0)
  • 2021-01-22 23:14

    In 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.

    0 讨论(0)
  • 2021-01-22 23:17

    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().

    0 讨论(0)
  • 2021-01-22 23:19

    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.

    0 讨论(0)
  • 2021-01-22 23:30

    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.

    0 讨论(0)
  • 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
    >>> {}
    
    0 讨论(0)
提交回复
热议问题