Using the result of type() in a boolean statement?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • dpapathanasiou

    Using the result of type() in a boolean statement?

    If I define a dictionary where one or more of the values is also a
    dictionary, e.g.:

    my_dict={"a":"s tring", "b":"string ", "c":{"x":"0","y ":"1"},
    "d":"string "}

    How can I use the output of type() so I can do one thing if the value
    is a string, and another if the value is a dictionary?

    i.e., I'd like to define a loop like this, but I'm not sure of the
    syntax:

    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


  • Terry Reedy

    #2
    Re: Using the result of type() in a boolean statement?

    dpapathanasiou wrote:
    If I define a dictionary where one or more of the values is also a
    dictionary, e.g.:
    >
    my_dict={"a":"s tring", "b":"string ", "c":{"x":"0","y ":"1"},
    "d":"string "}
    >
    How can I use the output of type() so I can do one thing if the value
    is a string, and another if the value is a dictionary?
    >
    i.e., I'd like to define a loop like this, but I'm not sure of the
    syntax:
    >
    for key, value in my_dict.items() :
    if type{value) is <type 'dict'>:
    if type(v) is dict:
    # do the dictionary logic
    elif type(value) is <type 'str'>:
    .... is str
    # do the string logic
    For built-in types without a built-in name, either import the types
    module or just make one yourself with type().
    >>func = type(lambda:1)
    >>func
    <class 'function'>
    >>bif = type(abs)
    >>bif
    <class 'builtin_functi on_or_method'>

    For userclass instances, use the userclass.

    Terry Jan Reedy


    Comment

    • Scott David Daniels

      #3
      Re: Using the result of type() in a boolean statement?

      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(valu e, dict):
      # do the dictionary logic
      elif isinstance(valu e, 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@A cm.Org

      Comment

      Working...