我想更改嵌套键的值,但出现此错误
key['score'] = new_score # come back to this
TypeError: 'str' object does not support item assignment
这是我的代码:
def add_score(self, obj):
for child in reversed(self.root.screen_two.ids.streak_zone.children):
name = child.text
with open("streak.json", "r+") as read_file:
data = json.load(read_file)
for key in data.keys():
if key == name:
score = data.get(key, {}).get('score')
new_score = score + 1
key['score'] = new_score # come back to this
这是我的json文件的样子:
{"one": {"action": "one",
"delay": 1557963534.4314187,
"seconds": 60,
"score": 0,
"delta": 1557963474.4314187},
"two": {"action": "two",
"delay": 1557963664.037102,
"seconds": 120,
"score": 0,
"delta": 1557963544.037102},
"three":{"action": "three",
"delay": 1557963792.4683638,
"seconds": 180,
"score": 0,
"delta": 1557963612.4683638}
}
如何更改json文件中的score
值?
答案 0 :(得分:0)
您应该能够直接更新字典元素。
替换以下内容
for key in data.keys():
if key == name:
score = data.get(key, {}).get('score')
new_score = score + 1
key['score'] = new_score # come back to this
使用
data[name]['score'] += 1
代码应该是
def add_score(self, obj):
for child in reversed(self.root.screen_two.ids.streak_zone.children):
name = child.text
with open("streak.json", "r+") as read_file:
data = json.load(read_file)
data[name]['score'] += 1
答案 1 :(得分:0)
在for循环中,您要遍历键数组(在您的情况下为['one','two','three']
。
尝试以下代码。希望这会有所帮助!
for key,value in data.items():
if key == name:
score = value['score']
new_score = score + 1
value['score'] = new_score
或者在下面使用一种衬纸,而不是在循环中使用
data[name]['score']+=1 #name='one'
在文件内编辑
with open('streak.json', 'r+') as f:
data = json.load(f)
data[name]['score']+=1
f.seek(0)
json.dump(data, f, indent=4)
f.truncate()
答案 2 :(得分:0)
这应该有效
with open("a.json", "r+") as read_file:
data = json.load(read_file)
data[name]['score'] += 1 # update score
with open("a.json", "w") as json_file: #write it back to the file
json.dump(data, json_file)