python ternary operator with assignment

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

提交回复
热议问题