Dictionary unpacking allows you to pass the key-value pairs of a dictionary as keyword arguments to a function or merge dictionaries:
def foo(a, b):
print(a+b)
my_dict = {"a": 1, "b": 2}
foo(**my_dict) # will print 3
Dictionary unpacking requires an object with methods __getitem__
and keys
or __getitem__
and
__getattr__
. This is the case for any mapping object such as
dict
. Using an object which doesn’t have these methods will raise a TypeError
.
Code examples
Noncompliant code example
class A:
pass
{'a': 10, 'b': 20, **A()} # Noncompliant
Compliant solution
class A:
def __getitem__(self, key):
return 2
def keys(self):
return ['1','2','3']
{'a': 10, 'b': 20, **A()} # => {'a': 10, 'b': 20, '1': 2, '2': 2, '3': 2}