search

Home  >  Q&A  >  body text

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

1

2

3

4

5

<code>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)])</code>

a and b should both be dict type data. How to understand this function, especially the last return? ?

学习ing学习ing2828 days ago884

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:

    1

    2

    3

    4

    5

    6

    <code class="python">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)}}</code>

    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

    1

    2

    3

    4

    5

    6

    7

    8

    <code>函数的作用合并两个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</code>

    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