pythonpython-3.xdictionaryfor-loopfor-comprehension

Python for comprehension with dict keys and values in else clause


Attached is my sample in below. Aim's want to update dict based on key which is present in another list. if key is present in the list update value +1 otherwise value -1. I tried with for comprehension approach and getting syntax error. through simple for loop , will solve the problem. but i am looking for approach with for comprehension.

enter image description here


Solution

  • It appears you are trying to use a conditional expression in a dictionary comprehension, but you actually wanted something like:

    {
      key: (data[key]+1 if key in data else data[key]-1)
      for key in list_update_keys
    }
    

    But this will result in a KeyError if the wide is triggered, since in that case the key is not in the dictionary.