Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Positively Identifying Python Variable Type

Trying to figure out how to positively identify the variable types.

w = {}
x = ""
y = 2
z = []

a = type(w)
b = type(x)
c = type(y)
d = type(z)

print(a)
print(b)
print(c)
print(d)

if a == 'dict': print ("Ok - its a dict")
elif a != 'dict': print ("Wrong - its not a dict")
    
if b == 'str': print ("Ok - its a string")
elif b != 'str': print ("Wrong - its not a string")
    
if c == 'int': print ("Ok - its an int")
elif c != 'int': print ("Wrong - its not an int")

if d == 'list': print ("Ok - okay, its a list")
elif d != 'list': print ("Wrong - its not a list") 

Generates the following output:

<class 'dict'>
<class 'str'>
<class 'int'>
<class 'list'>

The type() command generates a "class" structure, which makes it hard to positively identify the variable type in question.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there a way to get to the variable in the each class?

>Solution :

you need to address python data types correctly.

'dict' is not a data type but a string, however, dict is. It is a python data type and it belongs to <class 'dict'>.


w = {}
z = []
a = type(w)
b = type(z)
if a == dict: 
    print ("Ok - its a dict")
else:
    print('it is not')

if type(z) == list:
    print('z is a list')
else:
    print('z is not a list')

output:

Ok - its a dict
z is a list
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading