check if var is dict

Wildemar Wildenburger wildemar at freakmail.de
Mon Aug 13 13:41:54 CEST 2007


Astan Chee wrote:
> Hi,
> I have a variable, I want to check if it is a dictionary or a string.
> Is there any better way to do this than I've done. How I did it is by 
> doing a .items() and catching a AttributeError that it raises if its not 
> a dictionary.
> How do i properly do it?
>   
The way you did, actually :).
Look for "It's better to ask for forgiveness than for permission" (or 
so) and the term "duck typing". That's the way to do it in python.

And just for completeness' sake: You could have also checked for actual 
types via "isinstance(your_variable, dict) or "type(your_variable) is 
type(dict)" or ... But your approach is the recomended one.

/W



More information about the Python-list mailing list