Combining dictinoaries


In [1]:
default = {'a': 1, 'b': 2}
override = {'a': 3, 'c': 4}

In [2]:
# previous way
final = default.copy()
final.update(override)
final


Out[2]:
{'a': 3, 'b': 2, 'c': 4}

In [4]:
# with PEP 448
final = {**default, **override}
final


Out[4]:
{'a': 3, 'b': 2, 'c': 4}

In [7]:
final = {'a': 1, 'b': 2, **override}

Combining iterables


In [1]:
a = [1, 2, 3]
b = (4, 5, 6)
c = 'seven'  # alone
d = (x ** 3 for x in range(2, 5))
e = {'a': None, 'b': False}

In [2]:
joint = a + b


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-166c4836e45e> in <module>()
----> 1 joint = a + b

TypeError: can only concatenate list (not "tuple") to list

In [3]:
joint = a + list(b) + [c] + list(d) + sorted(e)
joint


Out[3]:
[1, 2, 3, 4, 5, 6, 'seven', 8, 27, 64, 'a', 'b']

In [22]:
joint = [*a, *b, c, *d, *sorted(e)]

In [21]:
joint


Out[21]:
[1, 2, 3, 4, 5, 6, 'seven', 'b', 'a']

In [28]:
'a: {} b: {} c: {}'.format(*[1, 2], 3)


Out[28]:
'a: 1 b: 2 c: 3'

In [31]:
[(*t, 'love') for t in final.items()]


Out[31]:
[('b', 2, 'love'), ('a', 3, 'love'), ('c', 4, 'love')]

In [7]:
def f(*args, **kwargs):
    return args, kwargs

In [8]:
f(**{'x': 2}, **{'x': 3})


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-56c423ed66fe> in <module>()
----> 1 f(**{'x': 2}, **{'x': 3})

TypeError: f() got multiple values for keyword argument 'x'

In [9]:
f(**{**{'x': 2}, **{'x': 3}})


Out[9]:
((), {'x': 3})

In [ ]: