我一直在嘗試合并這兩個:
A
{'v1': {'configuration': {'$schema': '...', 'network': {'$schema': '...'}}}}
E
{'v1': {'configuration': {'network': {'entries': {'$schema': '...'}}}}}
結果應該是:
{'v1': {'configuration': {'$schema': '...', 'network': {'$schema': '...', 'entries': {'$schema': '...'}}}}}
這是一組資料。所以我還有其他情況,其中
v1不只是configuration. 我要做的就是在字典中添加另一個字典中沒有的元素。A也總是有先例。
我嘗試使用以下示例之一:Python 合并兩個字典串列,其中字典鍵匹配
def merge_list_of_dicts(d1: dict, d2: dict):
def merge(list_of_dicts, current={}):
try:
get_key = lambda d: next(iter(d))
get_value = lambda d: next(iter(d.values()))
for d in list_of_dicts:
key = get_key(d)
value = get_value(d)
if key not in current:
current[key] = value
else:
current[key].update(value)
return current
except:
return current
return merge(d2, merge(d1))
print(merge_list_of_dicts(A, E))
我添加了嘗試/例外,因為沒有它我得到這個錯誤: AttributeError: 'str' object has no attribute 'values'
結果是:
{}
我也試過:
def myseconfunc(a, b):
print('===========')
a_keys = set(a.keys())
b_keys = set(b.keys())
commons = a_keys.intersection(b_keys)
#print('commons')
#print(commons)
for common in commons:
if type(a) == dict:
a = myseconfunc(a[common], b[common])
print('common:')
print(common)
print('a:')
print(a)
print('b:')
print(b[common])
a.update(b[common])
return a
但我明白了:
{'$schema': '...', 'entries': {'$schema': '...'}, 'network': {'entries': {'$schema': '...'}}, 'configuration': {'network': {'entries': {'$schema': '...'}}}}
有關更多詳細資訊,這里是列印的樣子:
===========
common:
network
a:
{'$schema': '...'}
b:
{'entries': {'$schema': '...'}}
===========
common:
configuration
a:
{'$schema': '...', 'entries': {'$schema': '...'}}
b:
{'network': {'entries': {'$schema': '...'}}}
===========
common:
v1
a:
{'$schema': '...', 'entries': {'$schema': '...'}, 'network': {'entries': {'$schema': '...'}}}
b:
{'configuration': {'network': {'entries': {'$schema': '...'}}}}
===========
我正在使用:Python 3.9.13
uj5u.com熱心網友回復:
這是一個通過您的示例的遞回演算法
import copy
A = {'v1': {'configuration': {'$schema': '...', 'network': {'$schema': '...'}}}}
E = {'v1': {'configuration': {'network': {'entries': {'$schema': '...'}}}}}
expected = {'v1': {'configuration': {'$schema': '...', 'network': {'$schema': '...', 'entries': {'$schema': '...'}}}}}
def safe_update_dict(d_to: dict, d_from: dict, inplace: bool=False):
def fn(d_to: dict, d_from: dict):
for k in d_from:
if k in d_to:
if isinstance(d_to[k], dict):
d_to[k] = fn(d_to[k], d_from[k])
else:
d_to[k] = d_from[k]
return d_to
if inplace:
return fn(d_to, d_from)
return fn(copy.deepcopy(d_to), d_from)
rtn = safe_update_dict(A, E)
print(str(expected) == str(rtn)) # True
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/505869.html
標籤:Python python-3.x 算法
上一篇:字串:如何將長文本字串中的名字和姓氏與其他單詞結合起來?
下一篇:多個排序陣列中的第K個最小元素
