Using the result of type() in a boolean statement?
Scott David Daniels
Scott.Daniels at Acm.Org
Wed Nov 12 17:37:40 EST 2008
dpapathanasiou wrote:
> ... I'd like to define a loop like this, ...
> 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
You're searching for "isinstance" (or possibly issubclass)
for key, value in my_dict.items():
if isinstance(value, dict):
# do the dictionary logic
elif isinstance(value, str): # use basestring for str & unicode
# do the string logic
Or, if you _must_ use type:
if issubclass(type(value), dict):
# do the dictionary logic
elif issubclass(type(value), str):
# do the string logic
--Scott David Daniels
Scott.Daniels at Acm.Org
More information about the Python-list
mailing list