Simple syntax error in Python if else dict comprehension

后端 未结 4 453
野性不改
野性不改 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:22
    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}
    
    0 讨论(0)
  • 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}
    
    0 讨论(0)
  • 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}
    
    0 讨论(0)
  • 2020-12-17 07:46

    This should solve your problem:

    >>> dict((k, d.get(k, 0)) for k in s)
    {'a': 0, 'c': 0, 'b': 5}
    
    0 讨论(0)
提交回复
热议问题