if I have dictionaries like :
a = {"param":["a","b","c"],"b":"aaa","c":"aAAaFfa"}
b = {"param":["a","b","c"],"b":"aaa","c":"aAAaFfa"}
and I need to validate they are equal and return true or false neglecting the case sensitivity
I have already tried :
shared_headers = {k: a[k] for k in a if k in b and a[k].lower() == b[k].lower()}
return len(shared_headers) == len(a)
but it only works fine when the dicts have no list values
CodePudding user response:
Try ''.join
- it can take any iterable of strings:
shared_headers = {k: a[k] for k in a if k in b and ''.join(a[k]).lower() == ''.join(b[k]).lower()}
return len(shared_headers) == len(a)
Note: this will think 'abc'
is the same as ['a', 'b', 'c']
Or, you could just compare the lowercase of the dicts:
return str(a).lower() == str(b).lower()
CodePudding user response:
I suggest you this quite long (but with comments) code. It gets the type of the dictionary values in order to adapt the comparison algorithm:
def check(a, b):
# Check if they have the same keys
if set(a) != set(b):
return False
# Check if they have the same values (neglecting the case sensitivity)
for k in a:
if isinstance(a[k], str):
# Here: value is a string
if not isinstance(b[k], str):
return False
if a[k].lower() != b[k].lower():
return False
elif isinstance(a[k], list):
# Here: value is a list
if not isinstance(b[k], list):
return False
if len(a[k]) != len(b[k]):
return False
for i,j in zip(a[k],b[k]):
if str(i).lower() != str(j).lower():
return False
else:
# Here: value is something else
print("Unexpected")
return False
return True