Recursively convert python object graph to dictionary

前端 未结 9 1619
既然无缘
既然无缘 2020-12-04 10:25

I\'m trying to convert the data from a simple object graph into a dictionary. I don\'t need type information or methods and I don\'t need to be able to convert it back to an

9条回答
  •  甜味超标
    2020-12-04 10:54

    I realize that this answer is a few years too late, but I thought it might be worth sharing since it's a Python 3.3+ compatible modification to the original solution by @Shabbyrobe that has generally worked well for me:

    import collections
    try:
      # Python 2.7+
      basestring
    except NameError:
      # Python 3.3+
      basestring = str 
    
    def todict(obj):
      """ 
      Recursively convert a Python object graph to sequences (lists)
      and mappings (dicts) of primitives (bool, int, float, string, ...)
      """
      if isinstance(obj, basestring):
        return obj 
      elif isinstance(obj, dict):
        return dict((key, todict(val)) for key, val in obj.items())
      elif isinstance(obj, collections.Iterable):
        return [todict(val) for val in obj]
      elif hasattr(obj, '__dict__'):
        return todict(vars(obj))
      elif hasattr(obj, '__slots__'):
        return todict(dict((name, getattr(obj, name)) for name in getattr(obj, '__slots__')))
      return obj
    

    If you're not interested in callable attributes, for example, they can be stripped in the dictionary comprehension:

    elif isinstance(obj, dict):
      return dict((key, todict(val)) for key, val in obj.items() if not callable(val))
    

提交回复
热议问题