Ignore specific keys in a dictionary using robot framework
How can I ignore specific keys in a dictionary using robot framework script? The dictionary is a nested dictionary.I tried with the below code but it removes the keys at the first level only. Any help is appreciated.
*** Variables ***
&{type} mobile=android mobileV2=windows
&{DICTIONARY} interface=ethernet interfaceId=default favorite=false mobile=android mobileV2=windows type=&{type}
*** Test Cases ***
Filter Dictionary Values
Log \nDictionaty values... : ${DICTIONARY} console=${True}
${d1_filtered} = Evaluate {k:v for k,v in ${DICTIONARY}.items() if k not in ('mobile','mobileV2')}
Log \nDictionaty filtered values... : ${d1_filtered} console=${True}
The resulting output log is given below.
Dictionaty filtered values... : {'interface': 'ethernet', 'interfaceId': 'default', 'favorite': 'false', 'type': {'mobile': 'android', 'mobileV2': 'windows'}}
Solution 1:
You can create your library and import it here. Using this answer the library can look something like this.
class MyLibrary:
def deleteKeys(self, dict_del, lst_keys: list):
for k in lst_keys:
try:
del dict_del[k]
except KeyError:
pass
for v in dict_del.values():
if isinstance(v, dict):
self.deleteKeys(v, lst_keys)
return dict_del
if __name__=="__main__":
mydict= {'interface': 'ethernet', 'interfaceId': 'default', 'favorite': 'false', 'mobile': 'android', 'mobileV2': 'windows', 'type': {'mobile': 'android', 'mobileV2': 'windows'}}
bad_keys = ['mobile','mobileV2']
lib = MyLibrary()
test = lib.deleteKeys(mydict, bad_keys)
print(test)
Here is the robot file:
***Settings***
Library ./MyLibrary.py
*** Variables ***
&{type} mobile=android mobileV2=windows
&{DICTIONARY} interface=ethernet interfaceId=default favorite=false mobile=android mobileV2=windows type=&{type}
@{remove_list} mobile mobileV2
*** Test Cases ***
Filter Dictionary Values
Log \nDictionaty values... : ${DICTIONARY}
${d1_filtered}= MyLibrary.deleteKeys ${DICTIONARY} ${remove_list}
Log \nDictionaty filtered values... : ${d1_filtered}