【问题标题】:How to flatten nested python dictionaries?如何展平嵌套的python字典?
【发布时间】:2016-08-25 01:41:15
【问题描述】:

我正在尝试展平嵌套字典:

dict1 = {
    'Bob': {
        'shepherd': [4, 6, 3],
        'collie': [23, 3, 45],
        'poodle': [2, 0, 6],
    },
    'Sarah': {
        'shepherd': [1, 2, 3],
        'collie': [3, 31, 4],
        'poodle': [21, 5, 6],
    },
    'Ann': {
        'shepherd': [4, 6, 3],
        'collie': [23, 3, 45],
        'poodle': [2, 10, 8],
    }
}

我想在列表中显示所有值: [4, 6, 3, 23, 3, 45, 2, 0, 6, 1, 2, 3,..., 2, 10, 8]

我的第一个想法是这样做:

dict_flatted = [ i for name in names.values() for dog in dogs.values() for i in dog]

虽然我得到了错误。我很乐意提供如何处理它的提示。

【问题讨论】:

  • 您遇到什么错误?您提到了“the”错误,但实际上并没有描述它。

标签: python dictionary


【解决方案1】:

您可以使用如下简单的递归函数。

def flatten(d):    
    res = []  # Result list
    if isinstance(d, dict):
        for key, val in d.items():
            res.extend(flatten(val))
    elif isinstance(d, list):
        res = d        
    else:
        raise TypeError("Undefined type for flatten: %s"%type(d))

    return res


dict1 = {
    'Bob': {
        'shepherd': [4, 6, 3],
        'collie': [23, 3, 45],
        'poodle': [2, 0, 6],
    },
    'Sarah': {
        'shepherd': [1, 2, 3],
        'collie': [3, 31, 4],
        'poodle': [21, 5, 6],
    },
    'Ann': {
        'shepherd': [4, 6, 3],
        'collie': [23, 3, 45],
        'poodle': [2, 10, 8],
    }
}

print( flatten(dict1) )

【讨论】:

  • 非常非常聪明。
  • 不错!谢谢!我稍微扩展了您的代码以允许在列表中进行递归。结果发布在下面。
【解决方案2】:

您正在尝试使用不存在的变量。

使用这个

dict_flatted = [ i for names in dict1.values() for dog in names.values() for i in dog]

【讨论】:

    【解决方案3】:

    递归函数可以是单行:

    def flatten(d):
        return d if isinstance(d, list) else sum((flatten(i) for i in d.values()), [])
    

    注意:是duplicate question的答案

    【讨论】:

      【解决方案4】:

      我从@DaewonLee 的代码开始,并将其扩展到更多数据类型并在列表中递归:

      def flatten(d):
          res = []  # type:list  # Result list
          if isinstance(d, dict):
              for key, val in d.items():
                  res.extend(flatten(val))
          elif isinstance(d, list):
              for val in d:
                  res.extend(flatten(val))
          elif isinstance(d, float):
              res = [d]  # type: List[float]
          elif isinstance(d, str):
              res = [d]  # type: List[str]
          elif isinstance(d, int):
              res = [d]  # type: List[int]
          else:
              raise TypeError("Undefined type for flatten: %s" % type(d))
          return res
      

      【讨论】:

        猜你喜欢
        • 2018-10-30
        • 2020-12-15
        • 1970-01-01
        • 1970-01-01
        • 2019-11-15
        • 2012-09-06
        • 2019-05-03
        • 1970-01-01
        • 2021-06-02
        相关资源
        最近更新 更多