аватар on5fydu8@gmail.com · 01.01.1970 03:00

Why can't you just take and fold two dictionaries?

& nbsp;

Why are lists, motorcades, sets, but dictionaries - you can’t?

If you don't like +, you can make fluent interface - so that dict.uPdate () is retued Self.

The best thing I found is dict (dict1, key1 = value1) . DATA-HIGHLIGHTED = ""> BASE_CONFIG = { 'KEY1' : 'Val1'} func1 (Base_config + { 'key2' : 'val2' }) func2 (base_config + { 'key3' : 'val3' })

& nbsp;

аватар on5fydu8@gmail.com · 01.01.1970 03:00

Update: Python 3.9 implements PEP 584 -- Add Union Operators To dict :

n
;>> {0: 'a', 1: 'b'} | {False: 'A', 2: 'C'}n{0: 'A', 1: 'b', 2: 'C'}n
n

combining dictionaries using | (union) operations: leftmost keys (as in | operations for set) the rightmost (later) values also win (as dict_add_keep_last() below).

n

There is also a local operation (it changes the dictionary) and you can transfer more than just dictionaries.:

n
>>> d = {0: 'a', 1: 'b'}n>"">'b'}n>>> d |= [(False, 'A'), (2, 'C'), 'C')]n>>>dn{0: 'A', 1: 'b', 2: 'C'}n2: 'C'}n
n
n

Old answer:

n

Because it is not clear which operation + should implement for dictionaries. And the preferred options for each specific case are easy to implement.

n

From ""The Zen of Python"" (import this) :

n
Explicit is better than implicit.nIn the face of ambiguity, refuse the temptation to guess.nThere should be one-- and preferably only one --obvious way to do it.n
n

BDFL (2009) :

n
n

Because there so many different ways to think about this, it's better not to guess and force the user to be explicit.

n
n

Guido (2019): Why operators are useful .seful .

n

For example (pseudo-code):

n
result = {'a': 1, 'b': 2} + {'a': 3, 'c': 0}n
n

re>n

Different answers are possible:

n
    n
  • n

    save only the latest values ( PEP-0584 behavior )

    n
    result = {'a': 3, 'b': 2, 'c': 0}n
    n

    can be implemented as follows:

    n
    defe class=""data-highlighted="">def dict_add_keep_last(a, b): # aka merged() or updated()n    d = a.copy()n    d.update(b)n    retu dn
    n

    ode>n

    In special cases where keys are strings, you can do without a function (Python 2 (CPython) also allows arbitrary keys), example :

    n
    result = dict(a, **b) # the result is the samen
    n

    Guido does not like this not like this construction.

    n

    Or for arbitrary dictionaries in Python 3.5 ( PEP 0448 -- Additional Unpacking Generalizations ):

    n
    result = {**a, **b}n
    n

    see Adding dictionaries together, Python (follow the links along the chain, there are good answers to each question).

    n
  • n
  • n

    save the first values (as close as possible to how | operation is implemented in set()):

    n
    result = {**b, **a} # Python 3.5, or else swap a, b: dict_add_keep_last(b, a)n
    n
  • n
  • n

    summarize the values as collections.Counter (Multiset semantics):

    n
    >">>>> from collections import Counte>n>>> Counter(a) + Counter(b)nCounter({'a': 4, 'b': 2})n
    n

    ass="">2})nn

    Keys with zero (and negative) values ('c') are not saved.

    n
  • n
  • n

    combine them in some other way so as not to lose information, for example, sum_dict() or:

    n
    result = {'a': [1, 3], 'b': 2, 'c': 0}n
    n

    Use-case: duplicate keys in a json object

    n
  • n
  • n

    fail in case of duplicate keys, an example .ample .

    n
  • n
n

None of the presented options is more obvious (more precisely, different people may consider different options more obvious). Moreover, each of these options has a right to exist and they are not always interchangeable. Different dictionary addition options are not used very often, so it is important that in each case it is explicitly indicated which type of operation is used and there is no need to guess (errors are less likely).

n

The idea has been discussed on the python-ideas mailing list several times.:

n
    n
  • ""Adding ""+"" and ""+="" operators to dict"" (2015)
  • n
  • ""adding dictionaries"" (2014)
  • n
  • ""dict '+' operator and slicing support for pop"" (2009)
  • n
n

Minor remarks (unrelated to the "why", but they are useful for the topic "putting two dictionaries together"):

n
    n
  • n

    the retu type for a + b expressions, as usual, is not obvious and may depend on the type of a and b for example, the expression a +=b, can ""change"" the type of a:

    n
    >>> from decimal import Decimaln>n&g="">>>> a = 1n>>> a += Decimal(2)n>>> anDecimal('3')n
    n
  • n
  • n

    also, in the case of multiple dictionaries, + syntax encourages inefficient (memory, execution time) code for large dictionaries, for example, a += b + c + d + . + c + .. (O(N*k**2)) can be written more efficiently as (O(N*k)):

    n
    for it in [b, c, d, ..]:n a.update(it)n
    n
  • n
  • n

    sometimes (for example, for large dictionaries, in which only some keys are interesting) you can "lazily" (O(k)) merge dictionaries using ChainMap:

    n
    try: n from collections import ChainMapnexcept ImportError: # Python 2n from ConfigParser import _Chainmap as ChainMapn
    n

    pylookup = ChainMap(locals(), globals(), vars(builtins))

    n
  • n
n
n
n

If you don't like +, you could also make a fluent interface so that dict.update() retus self.

n
n

Because in Python, methods that modify an object usually retu None, a typical example is some_list.sort() vs. sorted(some_list). Python follows the Command–query separation principle.

n

Latest

Similar