我有两本字典,如下所示。两个字典都有一个字典列表,作为与其properties
键关联的值;这些列表中的每个字典都有一个id
键。我希望将我的两个词典合并为一个词典,这样生成的词典中的properties
列表中每个id
只有一个词典
{
"name":"harry",
"properties":[
{
"id":"N3",
"status":"OPEN",
"type":"energetic"
},
{
"id":"N5",
"status":"OPEN",
"type":"hot"
}
]
}
另一份名单:
{
"name":"harry",
"properties":[
{
"id":"N3",
"type":"energetic",
"language": "english"
},
{
"id":"N6",
"status":"OPEN",
"type":"cool"
}
]
}
我试图实现的输出是:
"name":"harry",
"properties":[
{
"id":"N3",
"status":"OPEN",
"type":"energetic",
"language": "english"
},
{
"id":"N5",
"status":"OPEN",
"type":"hot"
},
{
"id":"N6",
"status":"OPEN",
"type":"cool"
}
]
}
由于id: N3
在两个列表中都很常见,因此这两个dict应该与所有字段合并。到目前为止,我已经尝试使用itertools
和
ds = [d1, d2]
d = {}
for k in d1.keys():
d[k] = tuple(d[k] for d in ds)
有人能帮我弄清楚吗
以下是一种方法:
输出:
将这两个对象视为各自列表中的元素可能会有所帮助。可能您还有其他具有不同
name
值的对象,例如可能来自JSON格式的REST请求然后可以对
name
和id
键执行left outer join:上面的想法是处理列表
a
中的名称和ID。按名称列出的名称和ID是Pythonset
的实例。所以成员总是独一无二的一旦有了这些集合,就可以对列表
b
的内容执行左外部联接或者
b
中有一个对象在a
中不存在(即共享一个公共的name
),在这种情况下,您可以按原样将该对象添加到结果中。但是如果在b
中有一个对象确实存在于a
(它共享一个公共的name
),那么您将迭代该对象的id
值,并按名称查找尚未在a
ID集中的ID。将缺少的属性添加到a
,然后将处理过的对象添加到结果中输出:
这不会对输入执行任何错误检查。这依赖于每个对象的
name
值是唯一的。因此,如果两个列表中的对象中都有重复的键,则可能会得到垃圾(不正确或意外的输出)相关问题 更多 >
编程相关推荐