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

Discussion in 'Python' started by dpapathanasiou, Nov 12, 2008.

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

    my_dict={"a":"string", "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
     
    dpapathanasiou, Nov 12, 2008
    #1
    1. Advertising

  2. dpapathanasiou

    Terry Reedy Guest

    dpapathanasiou wrote:
    > If I define a dictionary where one or more of the values is also a
    > dictionary, e.g.:
    >
    > my_dict={"a":"string", "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_function_or_method'>

    For userclass instances, use the userclass.

    Terry Jan Reedy
     
    Terry Reedy, Nov 12, 2008
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Mike Newton
    Replies:
    0
    Views:
    2,686
    Mike Newton
    Jul 27, 2004
  2. J Leonard
    Replies:
    4
    Views:
    12,753
    Mark Space
    Jan 19, 2008
  3. Gnarlodious

    Boolean result of divmod

    Gnarlodious, Jun 21, 2011, in forum: Python
    Replies:
    3
    Views:
    198
    Terry Reedy
    Jun 21, 2011
  4. Michael Tan
    Replies:
    32
    Views:
    1,021
    Ara.T.Howard
    Jul 21, 2005
  5. Metre Meter
    Replies:
    7
    Views:
    402
    Metre Meter
    Aug 6, 2010
Loading...

Share This Page