Simple syntax error in Python if else dict comprehension

后端 未结 4 454
野性不改
野性不改 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:39

    The expanded form of what you're trying to achieve is

    a = {}
    for k in v:
        a[k] = d[k] if k in d else 0
    

    where d[k] if k in d else 0 is the Python's version of ternary operator. See? You need to drop k: from the right part of the expression:

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

    You can write it concisely like

    a = {k: d.get(k, 0) for k in d}
    

提交回复
热议问题