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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • dudeja.rajat@gmail.com

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

    Hi,

    How to check if something is a list or a dictionary or just a string?
    Eg:

    for item in self.__libVerDi ct.itervalues() :
    self.cbAnalysis LibVersion(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
  • Jason Scheirer

    #2
    Re: How to check is something is a list or a dictionary or a string?

    On Aug 29, 9:16 am, dudeja.ra...@gm ail.com wrote:
    Hi,
    >
    How to check if something is a list or a dictionary or just a string?
    Eg:
    >
    for item in self.__libVerDi ct.itervalues() :
                self.cbAnalysis LibVersion(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.BooleanTy pe:
    ...: print "Boolean", item
    ...: elif type(item) is types.ListType:
    ...: print "List", item
    ...: elif type(item) is types.StringTyp e:
    ...: print "String", item
    ...: else:
    ...: print "Some other type", type(item), ':', item
    ...:
    ...:
    List []
    Some other type <type 'dict': {}
    Boolean False
    String HELLO

    Comment

    • George Sakkis

      #3
      Re: How to check is something is a list or a dictionary or a string?

      On Aug 29, 12:16 pm, dudeja.ra...@gm ail.com wrote:
      Hi,
      >
      How to check if something is a list or a dictionary or just a string?
      Eg:
      >
      for item in self.__libVerDi ct.itervalues() :
      self.cbAnalysis LibVersion(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

      Comment

      • Ken Starks

        #4
        Re: How to check is something is a list or a dictionary or a string?

        George Sakkis wrote:
        On Aug 29, 12:16 pm, dudeja.ra...@gm ail.com wrote:
        >Hi,
        >>
        >How to check if something is a list or a dictionary or just a string?
        >Eg:
        >>
        >for item in self.__libVerDi ct.itervalues() :
        > self.cbAnalysis LibVersion(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,



        (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

        Comment

        • josh logan

          #5
          Re: How to check is something is a list or a dictionary or a string?

          But this changes with Python 3, right?

          On Aug 30, 7:15 am, Ken Starks <stra...@lampsa cos.demon.co.uk wrote:
          George Sakkis wrote:
          On Aug 29, 12:16 pm, dudeja.ra...@gm ail.com wrote:
          Hi,
          >
          How to check if something is a list or a dictionary or just a string?
          Eg:
          >
          for item in self.__libVerDi ct.itervalues() :
                      self.cbAnalysis LibVersion(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,
          >

          >
          (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

          Comment

          • Ken Starks

            #6
            Re: How to check is something is a list or a dictionary or a string?

            josh logan wrote:
            But this changes with Python 3, right?
            >
            right!

            see


            (quote)
            Strings and Bytes

            * There is only one string type; its name is str but its behavior
            and implementation are like unicode in 2.x.
            * The basestring superclass has been removed. The 2to3 tool
            replaces every occurrence of basestring with str.
            * PEP 3137: There is a new type, bytes, to represent binary data
            (and encoded text, which is treated as binary data until you decide to
            decode it). The str and bytes types cannot be mixed; you must always
            explicitly convert between them, using the str.encode() (str -bytes)
            or bytes.decode() (bytes -str) methods.
            * All backslashes in raw strings are interpreted literally. This
            means that Unicode escapes are not treated specially.

            * PEP 3112: Bytes literals, e.g. b"abc", create bytes instances.
            * PEP 3120: UTF-8 default source encoding.
            * PEP 3131: Non-ASCII identifiers. (However, the standard library
            remains ASCII-only with the exception of contributor names in comments.)
            * PEP 3116: New I/O Implementation. The API is nearly 100%
            backwards compatible, but completely reimplemented (currently mostly in
            Python). Also, binary files use bytes instead of strings.
            * The StringIO and cStringIO modules are gone. Instead, import
            io.StringIO or io.BytesIO.
            * '\U' and '\u' escapes in raw strings are not treated specially.



            On Aug 30, 7:15 am, Ken Starks <stra...@lampsa cos.demon.co.uk wrote:
            >George Sakkis wrote:
            >>On Aug 29, 12:16 pm, dudeja.ra...@gm ail.com wrote:
            >>>Hi,
            >>>How to check if something is a list or a dictionary or just a string?
            >>>Eg:
            >>>for item in self.__libVerDi ct.itervalues() :
            >>> self.cbAnalysis LibVersion(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
            >

            Comment

            • Larry Bates

              #7
              Re: How to check is something is a list or a dictionary or a string?

              dudeja.rajat@gm ail.com wrote:
              Hi,
              >
              How to check if something is a list or a dictionary or just a string?
              Eg:
              >
              for item in self.__libVerDi ct.itervalues() :
              self.cbAnalysis LibVersion(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
              Are you sure that is what you want to do or do you want to make sure that
              "something" is an iterable. What if someone passed in a generator or a class
              instance that is iterable, do you really want to fail?

              -Larry

              Comment

              Working...