Using the result of type() in a boolean statement?

D

dpapathanasiou

If I define a dictionary where one or more of the values is also a
dictionary, e.g.:

my_dict={"a":"string", "b":"string", "c":{"x":"0","y":"1"},
"d":"string"}

How can I use the output of type() so I can do one thing if the value
is a string, and another if the value is a dictionary?

i.e., I'd like to define a loop like this, but I'm not sure of the
syntax:

for key, value in my_dict.items():
if type{value) is <type 'dict'>:
# do the dictionary logic
elif type(value) is <type 'str'>:
# do the string logic
# etc
 
T

Terry Reedy

dpapathanasiou said:
If I define a dictionary where one or more of the values is also a
dictionary, e.g.:

my_dict={"a":"string", "b":"string", "c":{"x":"0","y":"1"},
"d":"string"}

How can I use the output of type() so I can do one thing if the value
is a string, and another if the value is a dictionary?

i.e., I'd like to define a loop like this, but I'm not sure of the
syntax:

for key, value in my_dict.items():
if type{value) is <type 'dict'>:

if type(v) is dict:
# do the dictionary logic
elif type(value) is <type 'str'>:

.... is str
# do the string logic

For built-in types without a built-in name, either import the types
module or just make one yourself with type().
<class 'builtin_function_or_method'>

For userclass instances, use the userclass.

Terry Jan Reedy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top