Search code examples
pythonlistfor-looplist-comprehension

How can I convert this into list comprehension


I have a dictionary in which I need to append new values with keys from another dictionary, though i made the for loop working, I'm asked to make a list comprehension for it. can someone help me out in this

Code:

for key, value in functionParameters.items():
    if type(value) in [int, float, bool, str]:
       if key not in self.__variables:
          self.__variables[key] = value

any help will be appreciated...


Solution

  • Since you want to create/update a dict, you need to use dict comprehension -

    self.__variables = {**self.__variables, **{k: v for k, v in functionParameters.items() if type(v) in [int, float, bool, str] and k not in self.__variables}}
    

    Explanation -

    • z = {**x, **y} merges dicts x and y into a new dict z.
    • {k: v for k, v in functionParameters.items() if type(v) in [int, float, bool, str] and k not in self.__variables} mimics your for loop and creates a new dict
    • We are merging the original self.__variables dict with newly created dict above and saving it as self.__variables.

    here's a simplifed working example -

    functionParameters = {"20": 20, "string_val": "test", "float": 12.15, "pre-existing_key": "new-val", "new_type": [12, 12]}
    variables = {"old_key": "val", "pre-existing_key": "val"}
    variables = {**variables, **{k: v for k, v in functionParameters.items() if type(v) in [int, float, bool, str] and k not in variables}}
    print(variables)
    

    Prints -

    {'old_key': 'val', 'pre-existing_key': 'val', '20': 20, 'string_val': 'test', 'float': 12.15}
    

    Note that the value of the pre-existing_key key in output and missing new_type key since corresponding value is a list.