Dictionary membership verification unexpected behavior

An immovable object cannot be inserted into a dict. This is documented; there are good reasons for this.

However, I do not understand why this affects the membership test:

if value not in somedict:
    print("not present")

I assumed that a membership test can only return Trueor False. But when valuenot shaking, he fails with TypeError: unhashable type. I would say that it Trueshould be the correct answer for this test not in, because it is valueclearly not contained in somedict, and it does not matter at all that it cannot be inserted.

Another example:

try:
    result = somedict[value]
except KeyError:
    # handle the missing key

When the value does not shake, it fails with TypeError: unhashable type, I would expect KeyError.

also:

somedict.get(value, default)

does not return the default value, but throws it away TypeError.


, unhashable in somedict False , True False?


Update:

object.__contains__(self, item)

. true, , false .

( " - Python" )


:

, , dict.

# args = list of function arguments created from user input
# where "V1" stands for value1 and "V2" stands for value2
XLAT = {'V1': value1, 'V2': value2} 
args = [XLAT.get(a, a) for a in args]
function(*args)
+6
5

, , , - . - ( ), .

, , ", " ( " " ).

, .

, , , , , . I. e. , , . ( , ). , , , - , . , , .

, (, ), :

try:
    if strange_maybe_unhashable_value in my_dict:
        print("Yes, it in!")
    else:
        print("No, it not in!")
except TypeError:
    print("No, it not even hashable!")

KeyError:

try:
    result = somedict[value]
except (KeyError, TypeError):
    # handle the missing key

try:
    result = somedict[value]
except KeyError:
    # handle the missing key
except TypeError:
    # react on the thing being unhashable

, :

- (, ). , , , , . . - - . , ( ). , , , -. , , "" KeyError, TypeError.

+9

, , , : , : False. "", , , , .

0

, dict, , , , . , ; , .

, . , , , :

try:
    if value not in somedict:
        ...
except TypeError:
    ...
0

, . : unhashable .

, Counter, Dictionary, .

cnt.Add(x) # adds one to the counter
cnt.Count(x) # returns the number of occurences of x as seen by cnt, 0 if x has never been seen beofreL.

, , -, , . , , 0, .

, , , , . , .

0

:

if value not in somedict.values():
    print("not present")
-1

All Articles