NewJob
NewJob

Reputation: 69

Dict equivalency in python

I'd like to find out how dictionary equivalence is checked in python, depending on whether the same dictionary instance is used, or a different instance with the same values. I've found some stackoverflow posts hinting at the answer, but none stating it explicitely.

Basically, assuming I have an array of dictionaries, with various key/value pairs. If I now created a new instance of a dictionary, and performed an mydict in mylist check, when would the result of this check be True, and when would it be False?

Optimally, I'd hope that the behavior is as follows:

Same instance Different instance
Same value T T
Different value F F

However, it looks like the real result is something more like this:

Same instance Different instance
Same value T T
Different value T F

Is my second result guaranteed to always be the case? How does equivalence of dicts work exactly, in Python?

Also, what is the best way to check if a dict is in a list anyway? With the following code:

 if b not in last[a]:
     last[a][b] = [] #Since this happens in a for loop, just make sure the array is initialized
 newIni = {"val1": val1, "val2": val2}
 if newIni not in last[a][b]:
     # do stuff

Gives me the error unhashable type dict, which supposedly should only come up when trying to use dicts as a key, but here I'm using dicts as a value, so not sure what's going on...

Upvotes: 0

Views: 64

Answers (0)

Related Questions