您在编写python程序时遇到了问题,下面是代码 -
import json as j
import _collections
x=[('Victor','Microsoft',7),('David','Facebook','5'),('Stephen','Google',8)]
tab_d=['Name','Company','Exp']
db_data=[]
db_single={}
for i,data in enumerate(x):
db_single[tab_d[0]] = data[0]
db_single[tab_d[1]] = data[1]
db_single[tab_d[2]] = data[2]
db_data.append(db_single)
j=j.dumps(db_data)
file = open('firstjson.js', 'w')
file.write(j)
o / p显示我[{"Name": "Stephen", "Company": "Google", "Exp": 8}, {"Name": "Stephen", "Company": "Google", "Exp": 8}, {"Name": "Stephen", "Company": "Google", "Exp": 8}]
,即Stephen添加三次而不是添加所有成员。有人可能会告诉我我在做什么错误吗?
答案 0 :(得分:0)
问题是你只创建一个对象db_sigle
,它每次都会被附加,只有值不断变化。
你必须做出这样的改变:
...
for i,data in enumerate(x):
db_single={}
db_single[tab_d[0]] = data[0]
...
否则您的引用和更改相同的对象