Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Using the result of type() in a boolean statement?

Reply
Thread Tools

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

 
 
dpapathanasiou
Guest
Posts: n/a
 
      11-12-2008
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


 
Reply With Quote
 
 
 
 
Terry Reedy
Guest
Posts: n/a
 
      11-12-2008
dpapathanasiou wrote:
> 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().

>>> func = type(lambda:1)
>>> func

<class 'function'>
>>> bif = type(abs)
>>> bif

<class 'builtin_function_or_method'>

For userclass instances, use the userclass.

Terry Jan Reedy


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Boolean result of divmod Gnarlodious Python 3 06-21-2011 01:35 AM
Subtle difference between boolean value and boolean comparison? Metre Meter Javascript 7 08-06-2010 08:40 PM
is a "?" at end of method name only for boolean result? Greg Hauptmann Ruby 3 11-07-2008 04:38 AM
difference between 'boolean' and 'java.lang.Boolean' J Leonard Java 4 01-19-2008 02:56 AM
1. Ruby result: 101 seconds , 2. Java result:9.8 seconds, 3. Perl result:62 seconds Michael Tan Ruby 32 07-21-2005 03:23 PM



Advertisments