我正试图用字典类型信息更新json有效载荷,并保持关键位置与以前相同,因为它是我正在工作的任务所要求的。
注意我理解typedict的实现不允许重复密钥,但我确实需要这样做,所以任何变通或黑客的方法都会有所帮助。
我有一个从json文件加载的有效载荷
payload.json
{
"name": "",
"address": "",
"age": " ",
"ethnicities": "",
"select": "",
"sub-ethnicities": "",
"select": "",
"option1": "",
"option2": ""
}
加载
payload = json.load(open("payload.json"))
I have The info:
info = {
"name": "Spock",
"ethnicities": "Vulcan",
"select": "paternal",
"sub-ethnicities": "human",
"select": "maternal",
}
我正试图将上述信息插入有效载荷,并保持关键索引的方式。
预期结果为
{
"name": "Spock",
"address": "",
"age": "",
"ethnicities": "Vulcan",
"select": "paternal",
"sub-ethnicities": "human",
"select": "maternal",
"option1": "",
"option2": ""
}
谢谢你的好意。
Usingdata | info或data.update(信息)将删除重复的密钥,这违背了我试图存档的目标。
例如期望的结果是:
{
"name": "Spock",
"address": "",
"age": "",
"ethnicities": "Vulcan",
"select": "paternal",
"sub-ethnicities": "human",
"select": "maternal",
"Extra-ethnicities": "Asian",
"select": "Asian"
}
但是我得到的是重复的密钥被删除了。
"name": "Spock",
"address": "",
"age": "",
"ethnicities": "Vulcan",
"select": "paternal",
"sub-ethnicities": "human",
"Extra-ethnicities": "Asian",
}
在Python 3.9中作为Union操作符添加了用于此操作的操作符:
payload_with_info = payload | info
print(payload_with_info)
>>>
{
'address': '',
'age': ' ',
'ethnicities': 'Vulcan',
'name': 'Spock',
'option1': '',
'option2': '',
'select': 'maternal',
'sub-ethnicities': 'human'
}