def combine_dicts(a, b):
if b is None:
return a
return dict(a.items() + b.items() +
[(k, combine_dicts(a[k], b[k])) for k in set(b) & set(a)])
a and b should both be dict type data. How to understand this function, especially the last return? ?
为情所困2017-06-30 09:57:56
This is how it is written in Python 2. Come to Python version 3.6:
def dict_deep_merge(a, b):
if not b:
return a
return {**a, **b,
**{k: dict_deep_merge(a[k], b[k])
for k in set(a) & set(b)}}
It should be more efficient. Everything else is pretty much the same.
It’s not a god-level code, nor is it difficult to understand. Just recursively merge values with the same key. What you need to know:
dict’s items method
tuples
Gathering together
The meaning of dict parameters
淡淡烟草味2017-06-30 09:57:56
函数的作用合并两个dict
比如
a = {'a': {'A': 1}, 'b': 1}
b = {'a': {'B': 1}}
合并成
{'a': {'A': 1, 'B': 1}, 'b': 1}
set(b) & set(a)是取a,c的key交集,如上a,b的key交集为a, 再递归运行子dict
阿神2017-06-30 09:57:56
Ask a question, is there something wrong with the code? If the value in the same key is a string, will the items function report an error?