1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Dict merge in a dict comprehension

Discussão em 'Python' iniciado por Stack, Novembro 29, 2025.

  1. Stack

    Stack Membro Participativo

    In python 3.5, we can merge dicts by using double-splat unpacking

    >>> d1 = {1: 'one', 2: 'two'}
    >>> d2 = {3: 'three'}
    >>> {**d1, **d2}
    {1: 'one', 2: 'two', 3: 'three'}


    Cool. It doesn't seem to generalise to dynamic use cases, though:

    >>> ds = [d1, d2]
    >>> {**d for d in ds}
    SyntaxError: dict unpacking cannot be used in dict comprehension


    Instead we have to do reduce(lambda x,y: {**x, **y}, ds, {}), which seems a lot uglier. Why the "one obvious way to do it" is not allowed by the parser, when there doesn't seem to be any ambiguity in that expression?

    Continue reading...

Compartilhe esta Página