我试图编辑嵌套的字典名称我想在for循环中运行这个json文件以不同的名称
创建它5次{
"fruits": {
"color": "green",
"fruit": "apple",
}
}
如何改变水果到fruits1, fruits2, fruits3 ....等。我不想改变字典的内部,只改变主名(每次在foo循环时都是水果)
filename = "test.json"
for i in range(1,5+1):
with open(filename, 'r') as params:
data = json.load(params, object_pairs_hook=OrederedDict)
for key in data.items()
print(key[0]) # its print fruits
key[0] = "fruits"+str(i)
with open(filename, 'w') as json_file:
json.dump(data,json_file)
例子(后):
{
"fruits1": {
"color": "green",
"fruit": "apple",
}
}
不能更改Python字典中的键名。您可以做的是为现有键选择另一个名称,将原始键的值赋给该值,然后删除(del)原始键。
给定您的样本数据,您可以这样做:
D = {
"fruits": {
"color": "green",
"fruit": "apple",
}
}
D['fruits1'] = D['fruits']
del D['fruits']
print(D)
您可以使用.pop()
对于您提供给我们的样本数据,您可以这样做:
a = {
"fruits": {
"color": "green",
"fruit": "apple",
}
}
a['fruits1'] = a.pop('fruits')
print(a)