Tuesday, July 31, 2018

dictionary key type confusion isinstance python





I can't understand following execution. I expected different results.



>>> f = {'ms':'ma'}
>>> isinstance(f['ms'], type(str))
False


>>> isinstance(f['ms'], type(dict))
False

>>> type(f['ms'])


Answer



type(str) and type(dict) each return type, so you are checking if your objects are instances of type, which they are not.



If you want to check if something is a string, use




isinstance(f['ms'], str)


not



isinstance(f['ms'], type(str))


And if you want to test if something is a dict, you can use




isinstance(f['ms'], dict)


not



isinstance(f['ms'], type(dict))

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...