递归展平对象

时间:2018-12-30 21:46:50

标签: python object recursion

我有以下对象:

 ITEM_TRATAMENTOS ->{
      val viewHolderTratamentos = holder as ViewHolderItemTratamentos
      holder.add_field_btn.setOnClickListener {
                    inflater = Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
                    val rowView = inflater.inflate(R.layout.used_products_field, null)
                    // Add the new row.
                    parentLinearLayout?.addView(rowView, parentLinearLayout?.childCount!! - 1)
            }
  }

我想展平它以获得以下输出:

d={
   'CollectionTitleIDs': {
           '852070#TVEpisode': '12', 
           '852063#TVEpisode': '4', 
           '852067#TVEpisode': '9'
     }, 
    'ReleaseYear': '2005', 
    'TVSeriesID': '5638#TVSeries'
}

换句话说,如果键的值是字典,则将该键的键推到“ _Key”字段,将键的值推到“ Value”字段。

我在递归方面遇到了困难。目前我有这样的东西:

我目前拥有的是:

{
   'CollectionTitleIDs': [
      {"_Key": "852070#TVEpisode", "Value": "12"},
      {"_Key": "852063#TVEpisode", "Value": "4"},
      {"_Key": "852067#TVEpisode", "Value": "9"}
    ]
    'ReleaseYear': '2005', 
    'TVSeriesID': '5638#TVSeries'
}

请注意,上面的代码具有一个递归级别,但是“值”可能还会有(另一个)嵌套对象,在这种情况下,我们想再次提取_Key,Value。

3 个答案:

答案 0 :(得分:3)

您可以对列表进行解压缩:

d = {'CollectionTitleIDs': {'852070#TVEpisode': '12', '852063#TVEpisode': '4', '852067#TVEpisode': '9'}, 'ReleaseYear': '2005', 'TVSeriesID': '5638#TVSeries'}
new_d = {**d, 'CollectionTitleIDs':[{'_Key':a, 'Value':b} for a, b in d['CollectionTitleIDs'].items()]}

输出:

{'CollectionTitleIDs': 
  [{'_Key': '852070#TVEpisode', 'Value': '12'}, 
   {'_Key': '852063#TVEpisode', 'Value': '4'}, 
   {'_Key': '852067#TVEpisode', 'Value': '9'}], 
 'ReleaseYear': '2005', 'TVSeriesID': '5638#TVSeries'}

答案 1 :(得分:2)

代码应该比这更简单:

  1. 如果是列表,则返回展平对象的列表
  2. 如果是字典,则返回键/ val对象的列表
  3. 否则只需返回x

使用代码:

def flatten1(x):
    if isinstance(x, list):
        return [flatten1(y) for y in x]
    elif isinstance(x, dict):
        return [{"_Key": key, "Value": flatten1(value)}
                for key, value in x.items()]
    else:
        return x

但是在您的示例中,由于某种原因,顶级并没有被扁平化,而是常规的字典,所以只需这么做

def flatten(x):
    if isinstance(x, dict):
       return {key: flatten1(value) for key, value in x.items()}
    else:
       return flatten1(x)

flatten1甚至可以用作内部函数:

def flatten(x):
    def flatten1(x):
        if isinstance(x, list):
            return [flatten1(y) for y in x]
        elif isinstance(x, dict):
            return [{"_Key": key, "Value": flatten1(value)}
                    for key, value in x.items()]
        else:
            return x

    if isinstance(x, dict):
       return {key: flatten1(value) for key, value in x.items()}
    else:
       return flatten1(x)

答案 2 :(得分:0)

我的方法:

d={
   'CollectionTitleIDs': {
           '852070#TVEpisode': '12', 
           '852063#TVEpisode': '4', 
           '852067#TVEpisode': '9'
     }, 
    'ReleaseYear': '2005', 
    'TVSeriesID': '5638#TVSeries'
}

d['CollectionTitleIDs'] = list(map(lambda x: {'_Key': x[0], 'Value': x[1]}, d['CollectionTitleIDs'].items()))

#{
#  'CollectionTitleIDs': [
#    {'_Key': '852070#TVEpisode', 'Value': '12'},
#    {'_Key': '852063#TVEpisode', 'Value': '4'}, 
#    {'_Key': '852067#TVEpisode', 'Value': '9'}
#  ], 
#  'ReleaseYear': '2005', 
#  'TVSeriesID': '5638#TVSeries'
#}