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
In [82]: s = {'a', 'b', 'c'}
In [83]: d = {'b':5 }
In [85]: {key: d.get(key, 0) for key in s}
Out[85]: {'a': 0, 'b': 5, 'c': 0}
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}
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}
This should solve your problem:
>>> dict((k, d.get(k, 0)) for k in s)
{'a': 0, 'c': 0, 'b': 5}