You can always wrap it in a function:
def multiassign(d, keys, values):
d.update(zip(keys, values))
Even if you didn't know about update
, you could write it like this:
def multiassign(d, keys, values):
for k, v in zip(keys, values):
d[k] = v
Or you can even write a dict
subclass that gives you exactly the syntax you wanted:
class EasyDict(dict):
def __getitem__(self, key):
if isinstance(key, tuple):
return [super().__getitem__(k) for k in key]
else:
return super().__getitem__(key)
def __setitem__(self, key, value):
if isinstance(key, tuple):
self.update(zip(key, value))
else:
super().__setitem__(key, value)
def __delitem__(self, key, value):
if isinstance(key, tuple):
for k in key: super().__delitem__(k)
else:
super().__setitem__(key, value)
Now:
>>> d = {'a': 1, 'd': 4}
>>> multiassign(d, ['a', 'b', 'c'], [10, 200, 300])
>>> d
{'a': 10, 'b': 200, 'c': 300, 'd': 4}
>>> d2 = EasyDict({'a': 1, 'd': 4})
>>> d2['a', 'b', 'c'] = 100, 200, 300
>>> d2
{'a': 10, 'b': 200, 'c': 300, 'd': 4}
Just be aware that it will obviously no longer be possible to use tuples as keys in an EasyDict
.
Also, if you were going to use this for something serious, you'd probably want to improve the error handling. (d['a', 'b'] = 1
will give a cryptic message about zip argument #2 must support iteration
, d['a', 'b', 'c'] = 1, 2
will silently work and do nothing to c
, etc.)