-5

I'm looking for a way that convert all my outputs of a program (that I don't know what the types of them is) to dictionary... I think about a solution like this:

if type(body) != dict:
    body = {'result': body}

I know it is wrong! Is there any way that if the type of a variable was not dictionary, ourselves make a dictionary with that ?!

mahshid.r
  • 302
  • 4
  • 16
  • 2
    wrong why? it does the job. maybe using `isinstance` allows to check for child classes of `dict` though – Jean-François Fabre Jul 24 '17 at 07:14
  • 2
    https://stackoverflow.com/questions/1549801/differences-between-isinstance-and-type-in-python – perigon Jul 24 '17 at 07:16
  • 1
    Well hey you can actually put a dictionary in a dictionary. But can you specify a little more what you want, and post more code if you have more? – Shinra tensei Jul 24 '17 at 07:19
  • it's a big program in role of server that response to soap web services. i give wsdl and it's method, this program return answer of webservices on client side. and because of UI team i have to change the answer of web services to a correct json... @Shinra tensei – mahshid.r Jul 24 '17 at 07:31

1 Answers1

1

If your object isn't a dict but could be converted to a dict easily (e.g. list of pairs), you could use:

def make_a_dict(some_object):
    if isinstance(some_object, dict):
        return some_object
    else:
        try:
            return dict(some_object)
        except:
            return {'return': some_object}

print(make_a_dict({'a': 'b'}))
# {'a': 'b'}
print(make_a_dict([(1,2),(3,4)]))
# {1: 2, 3: 4}
print(make_a_dict(2))
# {'return': 2}
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124