gpt4 book ai didi

python - 如何在 python 中合并附加两个嵌套字典?

转载 作者:太空宇宙 更新时间:2023-11-04 08:13:52 28 4
gpt4 key购买 nike

例如我有两个字典:

schema = {
'type': 'object',
'properties': {
'reseller_name': {
'type': 'string',
},
'timestamp': {
'type': 'integer',
},
},
'required': ['reseller_name', 'timestamp'],
}

schema_add = {
'properties': {
'user_login': {
'type': 'string',
},
},
'required': ['user_login'],
}

如何将 next 与附加结果字典合并:

schema_result = {
'type': 'object',
'properties': {
'reseller_name': {
'type': 'string',
},
'timestamp': {
'type': 'integer',
},
'user_login': {
'type': 'string',
},
},
'required': ['reseller_name', 'timestamp', 'user_login'],
}

规则:

在示例中,propertiesrequiredschemescheme_add 的路径相同。

  1. 如果两个dict都有相同路径的dict,则它们按照相同的规则合并。
  2. 如果两个字典都有相同路径的列表,则将第一个列表与第二个列表相加。
  3. 如果两个字典都具有具有相同路径的简单值(或字典和非字典或列表和非列表),则第一个值将被第二个值覆盖。
  4. 如果只有一个字典有某个路径的键,而不是设置这个键和值。

最佳答案

不确定问题在哪里,但你写下来的方式几乎就像一个计算机程序,这个例子就像一个测试用例。为什么不从这里开始呢?

def add_dict(d1, d2):
newdict = {}
for (key, value) in d1.iteritems():
if key in d2: ...
#apply rules, add to newdict, use
else:
#simply add
for (key, value) in d2.iteritems():
if not key in d1:
# simply add
return newdict

这可能会写得更紧凑,但可能更容易编辑。

编辑..写完最后一条评论后,忍不住写了一个更好的实现

def merge_values(a,b):
if a==None or b==None:
return a or b
# now handle cases where both have values
if type(a)==dict:
return add_dict(a, b)
if type(a)==list:
...

def add_dict(d1,d2):
return dict(
[
(key,
merge_values(
d1.get(key,None),
d2.get(key,None)))
for key
in set(d1.keys()).union(d2.keys())
])

关于python - 如何在 python 中合并附加两个嵌套字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17857926/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com