如何防止for循环覆盖字典?

时间:2019-08-17 07:08:41

标签: python dictionary

我正在通过使用for循环为JSON文件创建字典。 但是我的for循环会覆盖条目

second_dict={}
third_dict={}

name=['suzen','lilly','sara']
hobbies=['chess','reading','dancing']
age=[13,14,15]

for i in range(len(name)):
    second_dict["hobbies"]=hobbies[i]
    second_dict["age"]=age[i]
    third_dict[name[i]]=second_dict
print(third_dict)

我得到了这个输出

{'suzen': {'hobbies': 'chess', 'age': 13},
'lilly': {'hobbies': 'chess', 'age': 13}, 
 'sara': {'hobbies': 'chess', 'age': 13}}

没有得到这个

{'suzen': {'hobbies': 'chess', 'age': 13},
 'lilly': {'hobbies': 'reading', 'age': 14}, 
 'sara': {'hobbies': 'dancing', 'age': 15}}

有人可以指出我的错误吗? 谢谢

1 个答案:

答案 0 :(得分:1)

new_dict={}
name=['suzen','lilly','sara']
hobbies=['chess','reading','dancing']
age=[13,14,15]
x = zip(name, hobbies, age)
for n,h,a in x:
    new_dict[n]={'hobbies': h, 'age': a}

print(new_dict) 

third_dict={}
name=['suzen','lilly','sara']
hobbies=['chess','reading','dancing']
age=[13,14,15]

for i in range(len(name)):
    second_dict={}
    second_dict["hobbies"]=hobbies[i]
    second_dict["age"]=age[i]

    third_dict[name[i]]=second_dict
print(third_dict)

正如注释中所指出的,您应该为每个second_dict创建一个新对象,共有3个second_dict