search

Home  >  Q&A  >  body text

Please help me interpret a piece of divine Python code, thank you! !

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学习ing2705 days ago811

reply all(3)I'll reply

  • 为情所困

    为情所困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

    • Addition of
    • tuples

    • Gathering together

    • The meaning of dict parameters

    reply
    0
  • 淡淡烟草味

    淡淡烟草味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

    reply
    0
  • 阿神

    阿神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?

    reply
    0
  • Cancelreply