我有2个dict,一个原始,一个用于同时将原始密钥映射到另一个值,例如:
原始字典
built_dict={'China':{'deportivo-cuenca-u20':{'danny':'test1'}},
'Germany':{'ajax-amsterdam-youth':{'lance':'test2'}}}
映射字典
club_team_dict={'deportivo-cuenca-u20':'deportivo','ajax-amsterdam-youth':'ajax'}
如果我使用以下代码更改原始字典的嵌套字典的键,则效果很好,例如
def club2team(built_dict,club_team_dict):
for row in built_dict:
# print test_dict[row]
for sub_row in built_dict[row]:
for key in club_team_dict:
# the key of club_team_dict must be a subset of test_dict,or you have to check it and then replace it
if sub_row==key:
built_dict[row][club_team_dict[sub_row]] = built_dict[row].pop(sub_row)
return built_dict
和结果
{'Germany': {'ajax': {'lance': 'test2'}}, 'China': {'deportivo': {'danny': 'test1'}}}
到目前为止一直很好,但是如果我有一个多键映射到同一个键的dict,例如,我原来的dict就像
built_dict={'China':{'deportivo-cuenca-u20':{'danny':'test1'}},
'Germany':{'ajax-amsterdam-youth':{'lance':'test2'},
'ajax-amsterdam':{'tony':'test3'}}}
和映射dict有多个1键映射到相同的值,如:
club_team_dict={'deportivo-cuenca-u20':'deportivo',
'ajax-amsterdam-youth':'ajax',
'ajax-amsterdam':'ajax'}
正如您所看到的,'ajax-amsterdam-youth'
和'ajax-amsterdam-youth'
都映射到'ajax'
,问题是当我使用相同的代码执行它时,原始dict的大小已更改在迭代期间
RuntimeError: dictionary changed size during iteration
我希望得到一个带有嵌套列表的结果,就像这个
一样{'Germany': {'ajax':[{'lance': 'test2'},
{'tony' : 'test3'}]}},
'China': {'deportivo': [{'danny': 'test1'}]}}
任何帮助都将不胜感激,谢谢,我将一直在寻找答案。
答案 0 :(得分:0)
我找到了解决方案,代码:
def club2team(built_dict,club_team_dict):
for row in built_dict:
# print test_dict[row]
for sub_row in built_dict[row].keys():
for key in club_team_dict:
# the key of club_team_dict must be a subset of test_dict,or you have to check it and then replace it
if sub_row==key:
# built_dict[row][club_team_dict[sub_row]] = built_dict[row].pop(sub_row)
built_dict[row].setdefault(club_team_dict[sub_row],[]).append(built_dict[row].pop(sub_row))
return built_dict
注意for sub_row in built_dict[row].keys():
和setdefault()
方法,我以前认为在python 2.7
中,dict的默认迭代只是迭代keys(),但这次它证明它有点不同,也许你有更好的解决方案,请告诉我,它会很感激,谢谢