以下是我的示例代码:
def clean(record):
record.pop('configurable_fields')
record.pop('applied_discounts')
record.pop('product_options')
for key, value in record.items():
if value is None:
record.pop(key)
return record
我收到此错误:
Traceback (most recent call last):
File "C:\Users\Filipe\Dropbox\code\bigAnalysis\finalized scripts\importer.py", line 76, in <module>
process_file('allOrderProductsData')
File "C:\Users\Filipe\Dropbox\code\bigAnalysis\finalized scripts\importer.py", line 73, in process_file
process_line(line)
File "C:\Users\Filipe\Dropbox\code\bigAnalysis\finalized scripts\importer.py", line 58, in process_line
product_id = dump_record('package', clean(package)) # id of recently created record
File "C:\Users\Filipe\Dropbox\code\bigAnalysis\finalized scripts\importer.py", line 40, in clean
for key, value in record.items():
RuntimeError: dictionary changed size during iteration
我尝试了一些我在其他线程中找到的解决方案,比如使用copy.deecopy,但到目前为止它们都没有。
答案 0 :(得分:5)
使用
for key, value in list(record.items()):
而不是
for key, value in record.items():
这样,你就可以冻结&#34;要迭代的项列表。 record.items()
是一个仍然持有对原始字典的引用的生成器。 list(record.items())
是一个独立的列表。
答案 1 :(得分:1)
为避免在迭代期间更改dict大小,您可以改为返回一个新的dict:
def clean(record):
record.pop('configurable_fields')
record.pop('applied_discounts')
record.pop('product_options')
return {k: v for k, v in record.items() if v is not None}