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

Jason Scheirer jason.scheirer at gmail.com
Fri Aug 29 12:52:14 EDT 2008


On Aug 29, 9:16 am, 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?
>
> Thanks,
> Rajat

type() and probably you want to import the types library as well.

In [1]: import types

In [2]: a = {1: {}, False: [], 'yes': False, None: 'HELLO'}

In [3]: a.values()
Out[3]: [[], {}, False, 'HELLO']

In [4]: [type(item) for item in a.itervalues()]
Out[4]: [<type 'list'>, <type 'dict'>, <type 'bool'>, <type 'str'>]

In [6]: for item in a.itervalues():
   ...:     if type(item) is types.BooleanType:
   ...:         print "Boolean", item
   ...:     elif type(item) is types.ListType:
   ...:         print "List", item
   ...:     elif type(item) is types.StringType:
   ...:         print "String", item
   ...:     else:
   ...:         print "Some other type", type(item), ':', item
   ...:
   ...:
List []
Some other type <type 'dict'> : {}
Boolean False
String HELLO



More information about the Python-list mailing list