3

I want to compare dictionaries in python. I know that I can simply do a == b, if a and b are dictionaries. This also works for nested dictionaries, where a and b contain dictionaries themselves. However, it does not work if a and b contain numpy arrays of size>1:

import numpy as np
a = {"1": np.array([1, 2])}
b = {"1": np.array([1, 2])}
a == b

I get this error:

Traceback (most recent call last):
File "", line 1, in
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I did check: this post and found the suggestion of import deepdiff from sumbudu which does what I want. However, is there an easier way using == and catching the error somehow?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Marti
  • 31
  • 3

1 Answers1

0

Like this?

def equal_dictionaries(dic1, dic2):
    for key, value in dic1.items():
        key1 = key
        value1 = value
    for key, value in dic2.items():
        key2 = key
        value2 = value
    if np.array_equal(value1, value2) == False or key1 != key2:
        return False
    else:
        return True
DarkDrassher34
  • 69
  • 3
  • 15