How to convert an OrderedDict into a regular dict in python3

后端 未结 8 630
天命终不由人
天命终不由人 2020-12-04 09:43

I am struggling with the following problem: I want to convert an OrderedDict like this:

OrderedDict([(\'method\', \'constant\'), (\'data\', \'1.         


        
8条回答
  •  忘掉有多难
    2020-12-04 10:00

    A version that handles nested dictionaries and iterables but does not use the json module. Nested dictionaries become dict, nested iterables become list, everything else is returned unchanged (including dictionary keys and strings/bytes/bytearrays).

    def recursive_to_dict(obj):
        try:
            if hasattr(obj, "split"):    # is string-like
                return obj
            elif hasattr(obj, "items"):  # is dict-like
                return {k: recursive_to_dict(v) for k, v in obj.items()}
            else:                        # is iterable
                return [recursive_to_dict(e) for e in obj]
        except TypeError:                # return everything else
            return obj
    

提交回复
热议问题