Tuesday 31 July 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...