How to check is something is a list or a dictionary or a string?

Ken Starks straton at lampsacos.demon.co.uk
Sat Aug 30 13:15:15 CEST 2008


George Sakkis wrote:
> On Aug 29, 12:16 pm, dudeja.ra... at gmail.com wrote:
>> Hi,
>>
>> How to check if something is a list or a dictionary or just a string?
>> Eg:
>>
>> for item in self.__libVerDict.itervalues():
>>             self.cbAnalysisLibVersion(END, item)
>>
>> where __libVerDict is a dictionary that holds values as strings or
>> lists. So now, when I iterate this dictionary I want to check whether
>> the item is a list or just a string?
> 
> if isinstance(item,basestring):
>    # it's a string
>     ...
> else: # it should be a list
>    # typically you don't have to check it explicitly;
>    # even if it's not a list, it will raise an exception later anyway
> if you call a list-specific method
> 
> 
> HTH,
> George

For a bit more explanation see, for example,

http://evanjones.ca/python-utf8.html

(Quote)
Working With Unicode Strings

Thankfully, everything in Python is supposed to treat Unicode strings 
identically to byte strings. However, you need to be careful in your own 
code when testing to see if an object is a string. Do not do this:

if isinstance( s, str ): # BAD: Not true for Unicode strings!

Instead, use the generic string base class, basestring:

if isinstance( s, basestring ): # True for both Unicode and byte strings



More information about the Python-list mailing list