将新的k:v对递归添加到嵌套字典

问题描述

我有一本嵌套的字典,在任何地方我都可以了解国家/地区信息。我正在应用从一个名为to_code()的库中提取的国家/地区归一化函数,该函数会吐出所传递字符串的ISO代码。

这是我的职能:

def update_country(dictionary):    
   for k,v in dictionary.items():
       if 'country' in k:
           dictionary[k+"_iso"] = to_code(v,fuzzy=True)
           
       elif isinstance(v,dict):
           for result in update_country(dictionary=v):
               yield result
               
       elif isinstance(v,list):
           for d in v:
               if isinstance(d,dict):
                   for result in update_country(dictionary=d):
                       yield result

想象一下这个嵌套的JSON

JSON = {"company_code": "123456","name": "Astrocom AG","officers": [{"name": "Abigail Kaloomp","country_of_residence": "bvi"},{"name": "EXPONET limited","address": {"address_line_1": "somewhere","address_line_2": "somewhere_else","country": "united kingdom"}}],"country": "italia"}}

我跑步时

from pprint import pprint
list(update_country(JSON))
pprint(JSON)

我收到以下错误:

Traceback (most recent call last):
  File "/home/gabri/.local/lib/python3.8/site-packages/IPython/core/interactiveshell.py",line 3417,in run_code
    exec(code_obj,self.user_global_ns,self.user_ns)
  File "<ipython-input-39-4ac13e957742>",line 1,in <module>
    list(update_country(JSON))
  File "<ipython-input-38-8f467b1cdf1b>",line 7,in update_country
    for result in update_country(dictionary=v):
  File "<ipython-input-38-8f467b1cdf1b>",line 2,in update_country
    for k,v in dictionary.items():
RuntimeError: dictionary changed size during iteration

我了解-实际上,如果我不是尝试插入新密钥,而是通过替换以下两行来更新现有密钥:

           dictionary[k+"_iso"] = to_code(v,fuzzy=True)
           # becomes
           dictionary[k] = to_code(v,fuzzy=True)  # overwrite existing value

然后我得到一个JSON,其中的国家/地区代码具有ISO代码。

问题是我需要两个。使用这种逻辑完全可行吗?还是在迭代过程中无法更改字典?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)