仍然在学习Python并试图组合2个JSON对象。
主数据集:
{
"form-fields": [
{"type": "text", "x-position": 0, "y-position": 0, "field": "buyer-1"},
{"type": "text", "x-position": 0, "y-position": 10, "field": "buyer-2"}
]
}辅助数据集:
{
"form-data": [
{"field": "buyer-1", "value": "John Smith"},
{"field": "buyer-2", "value": "Susan Smith"}
]
}预期的结果:将"value“附加到原始对象的。
{
"form-fields": [
{"type": "text", "x-position": 0, "y-position": 0, "field": "buyer-1", "value": "John Smith"},
{"type": "text", "x-position": 0, "y-position": 10, "field": "buyer-2", "value": "Susan Smith"}
]
}发布于 2022-06-11 18:06:38
我假定这些字段在主字段和次字段之间没有顺序。计划是创建一个字典调用update,其中key=field和value =备用值。然后更新主服务器。
primary = {
"form-fields": [
{"type": "text", "x-position": 0, "y-position": 0, "field": "buyer-1"},
{"type": "text", "x-position": 0, "y-position": 10, "field": "buyer-2"}
]
}
secondary = {
"form-data": [
{"field": "buyer-1", "value": "John Smith"},
{"field": "buyer-2", "value": "Susan Smith"}
]
}
update = {
record["field"]: record["value"]
for record in secondary["form-data"]
}
# update is {'buyer-1': 'John Smith', 'buyer-2': 'Susan Smith'}
for record in primary["form-fields"]:
if record["field"] in update:
record["value"] = update[record["field"]]结果是primary变成了
{
"form-fields": [
{
"type": "text",
"x-position": 0,
"y-position": 0,
"field": "buyer-1",
"value": "John Smith"
},
{
"type": "text",
"x-position": 0,
"y-position": 10,
"field": "buyer-2",
"value": "Susan Smith"
}
]
}发布于 2022-06-11 18:02:39
假设长度和索引在两本字典中是相同的,
primary = {
"form-fields": [
{"type": "text", "x-position": 0, "y-position": 0, "field": "buyer-1"},
{"type": "text", "x-position": 0, "y-position": 10, "field": "buyer-2"}
]
}
sec = {
"form-data": [
{"field": "buyer-1", "value": "John Smith"},
{"field": "buyer-2", "value": "Susan Smith"}
]
}
pl = primary.get("form-fields")
sl = sec.get("form-data")
for index, prim_val in enumerate(pl):
sec_val = sl[index]
prim_val.update(sec_val)
print(primary)合并字典的示例代码
marks = {'Physics':67, 'Maths':87}
internal_marks = {'Practical':48}
marks.update(internal_marks)
print(marks)
# Output: {'Physics': 67, 'Maths': 87, 'Practical': 48}https://stackoverflow.com/questions/72586702
复制相似问题