Simple syntax error in Python if else dict comprehension

后端 未结 4 460
野性不改
野性不改 2020-12-17 07:00

I have a set and dictionary and a value = 5

v = s = {\'a\', \'b\', \'c\'}
d = {\'b\':5 //<--new value}

If the key \'b\' in dictionary d

4条回答
  •  清歌不尽
    2020-12-17 07:27

    You can't use a ternary if expression for a name:value pair, because a name:value pair isn't a value.

    You can use an if expression for the value or key separately, which seems to be exactly what you want here:

    {k: (d[k] if k in v else 0) for k in v}
    

    However, this is kind of silly. You're doing for k in v, so every k is in v by definition. Maybe you wanted this:

    {k: (d[k] if k in v else 0) for k in d}
    

提交回复
热议问题