Please help me interpret a piece of divine Python code, thank you! !
学习ing
学习ing 2017-06-30 09:55:56
0
3
745
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? ?

学习ing
学习ing

reply all (3)
为情所困

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

  • Addition of
  • tuples

  • Gathering together

  • The meaning of dict parameters

    淡淡烟草味
    函数的作用合并两个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
      阿神

      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?

        Latest Downloads
        More>
        Web Effects
        Website Source Code
        Website Materials
        Front End Template
        About us Disclaimer Sitemap
        php.cn:Public welfare online PHP training,Help PHP learners grow quickly!