Home > database >  How can I convert this into list comprehension
How can I convert this into list comprehension

Time:03-12

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...

CodePudding user response:

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.

CodePudding user response:

It's not correct to check if a key is used in an array or not in this way:

if key not in self.__variables: # not correct

if you do this it checks if the key exists as a value inside self.__variables

I don't know your reason to do this!, but you can use try & except to handle it like this:

for key, value in functionParameters.items():
    if type(value) in [int, float, bool, str]:
       try: 
          if self.__variables[key] is not None:
             self.__variables[key] = value
       except Exception ignored:
             pass

CodePudding user response:

you are supposed to use dict comprehension for this. The code should be like this

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