迭代过程中递归方法改变字典

时间:2018-06-19 00:01:16

标签: python python-3.x recursion ordereddictionary

尝试在类中使用递归方法来展平嵌套的OrderedDicts。结果是 RuntimeError:字典在迭代期间改变了大小

我获得了OrderedDicts列表。大多数OrderedDicts都是简单的Key:string-value属性,但是某些值包含另一个OrderedDict。这种嵌套可以达到几个层次。这是一个非常简化的样本:

records = [
    OrderedDict([
        ('rec-1_field-1', 'r1f1_value'),
        ('rec-1_field-2', 'r1f2_value'),
        ('rec-1_nest-1', OrderedDict([
            ('n1_field-1', 'n1f1_value'),
            ('n1_field-2', 'n1f2_value')
            ])
         )
        ]),
    OrderedDict([
        ...
        ])
]

我的目标是取消嵌套这些OrderedDicts,以便上面开始转换成这个(注意我想要的“higherKey.lowerKey”命名法):

flatRecords = [
    {'rec-1_field-1':'r1f1_value',
    'rec-1_field-2':'r1f2_value',
    'rec-1_nest-1.n1_field-1':'n1f1_value',
    'rec-1_nest-1.n1_field-2':'n1f2_value'},
    ...
    ]

这是我的代码的简化版本。我将每个OrderedDict提供给一个方法,该方法在找到嵌套的OrderedDict时进行递归。我想我在递归中覆盖了我的flatRecord Dict,但无法确定如何纠正。

class unNested():
    def __init__(self):
        pass
    def flatResults(self, OD):
        self.OD = OD
        self.flattenedRecords = []
        for eachRecord in self.OD:
            self.flattenedRecords.append(self.flatten(eachRecord))
        return self.flattenedRecords
    def flatten(self, record):
        self.record = record
        self.flatRecord = {}
        for eachKey in self.record:
            if isinstance(self.record[eachKey], dict):
                self.subRecord = self.flatten(self.record[eachKey])
                for eachSub in self.subRecord:
                    self.key = eachKey + '.' + eachSub
                    self.flatRecord[self.key] = self.record[eachSub]
            else:
                self.flatRecord[eachKey] = self.record[eachKey]
        return self.flatRecord

因此,以下代码段导致“RuntimeError:字典在迭代期间更改了大小”

records = [
    OrderedDict([
        ('rec-1_field-1', 'r1f1_value'),
        ('rec-1_field-2', 'r1f2_value'),
        ('rec-1_nest-1', OrderedDict([
            ('rec-1_nest-1_field-1', 'r1n1f1_value'),
            ('rec-1_nest-1_field-2', 'r1n1f2_value')
            ])
         )
        ]),
    OrderedDict([
        ('rec-2_field-1', 'r2f1_value'),
        ('rec-2_field-2', 'r2f2_value'),
        ('rec-2_nest-1', OrderedDict([
            ('rec-2_nest-1_field-1', 'r2n1f1_value'),
            ('rec-2_nest-1_field-2', 'r2n1f2_value')
            ])
         )
        ])
    ]
crush = unNested()
crush.flatResults(records)

我确定这是一个业余的错误,但我很想听到任何想法或指导。谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用展平方法:

from collections import OrderedDict
records = [OrderedDict([('rec-1_field-1', 'r1f1_value'), ('rec-1_field-2', 'r1f2_value'), ('rec-1_nest-1', OrderedDict([('n1_field-1', 'n1f1_value'), ('n1_field-2', 'n1f2_value')]))])]
def flatten(d, last=''):
   for a, b in d.items():
      if not isinstance(b, OrderedDict):
         yield (f'{last}.{a}' if last else a, b)
      else:
         yield from flatten(b, last = a)

final_result = dict(flatten(records[0]))

输出:

{'rec-1_field-1': 'r1f1_value', 'rec-1_field-2': 'r1f2_value', 'rec-1_nest-1.n1_field-1': 'n1f1_value', 'rec-1_nest-1.n1_field-2': 'n1f2_value'}

为列表中的每个元素创建展平结构:

final_result = [dict(flatten(i)) for i in records]