在特定位置后向字典添加新键值



有一个字典是这样的

[
{
"Article": 7566746,
"Code": 100,
"Price": "151",
"Teg": "",
"Specifications": {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
}
]

标签"需要添加2行。写了一个简短的代码,但是它把值放在列表的末尾,但是它们需要在"标签">

之后。我代码:

with open("_test_result.json", encoding="utf-8") as file:
result_list = json.load(file)

for i in result_list[:2]:
i['filter'] = ''
i['teg2'] = ''
print(i)

更新的代码(感谢Kelly Bundy的两个细致的建议):

def insert_in_dictionary(dictionary, index, keys_list, values_list):
items = list(dictionary.items())
items[index:index]=list(zip(keys_list,values_list))
return dict(items)
with open("_test_result.json", encoding="utf-8") as file:
result_list = json.load(file)

for i in range(len(result_list)):
position = 4 # The key 'Teg' is in 4th position
keys_list = ['filter', 'teg2']
values_list = ['', '']
result_list[i] = insert_in_dictionary(result_list[i],position,keys_list,values_list)
print(result_list[i])

这可能有帮助:

import ast
with open('file.json','r') as f:
lines = f.readlines()
nlines = []
for line in lines:
if 'Teg' in line:
lines.append(line1)
lines.append(line2)
dictionary = ast.literal_eval(''.join(lines))

相关内容

  • 没有找到相关文章

最新更新