Jan-16-2020, 02:19 AM
i have 2 or more dictionaries to merge. they always have different keys. is there a way to do this in one expression? the .update() method returns None so it is unusable for this.
**
dictionary unpacking operators.>>> x = {'a': 1, 'b': 2} >>> y = {'c': 999, 'd': 200} >>> z = {**x, **y} >>> z {'a': 1, 'b': 2, 'c': 999, 'd': 200}
my_function(**merged_dict)and that will be the only use for the merged dictionary ... both parts being used for keyword arguments in the function call ... like:
my_function(**{**dicta,**dictb})is that the way to do it even for keyword arguments?
spam = {'a':1, 'b':2} eggs = {'c':3, 'd':4} def foo(*args, **kwargs): for key, value in kwargs.items(): print(f'{key} -> {value}') foo(**spam, **eggs)
Output:a -> 1
b -> 2
c -> 3
d -> 4
or to extend it with positional arguments:spam = {'a':1, 'b':2} eggs = {'c':3, 'd':4} def foo(*args, **kwargs): for arg in args: print(arg) for key, value in kwargs.items(): print(f'{key} -> {value}') foo('boo', 'woo', **spam, **eggs)
Output:boo
woo
a -> 1
b -> 2
c -> 3
d -> 4
orspam = {'a':1, 'b':2} eggs = {'c':3, 'd':4} bar = ['boo', 'woo'] def foo(*args, **kwargs): for arg in args: print(arg) for key, value in kwargs.items(): print(f'{key} -> {value}') foo(*bar, **spam, **eggs)
Output:boo
woo
a -> 1
b -> 2
c -> 3
d -> 4
>>> from collections import ChainMap >>> spam = {'a':1, 'b':2} >>> eggs = {'c':3, 'd':4} >>> chained = ChainMap(spam, eggs) >>> chained ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}) >>> eggs['e'] = 5 >>> chained ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4, 'e': 5}) >>> spam['c'] = 'c' >>> chained ChainMap({'a': 1, 'b': 2, 'c': 'c'}, {'c': 3, 'd': 4, 'e': 5}) >>> dict(chained) >>> {'c': 'c', 'd': 4, 'e': 5, 'a': 1, 'b': 2}