A shorter version, functionally equivalent to yours:
def dict_zip(*dicts):
return {k: [d[k] for d in dicts] for k in args[0].keys()}
That's assuming all dicts have the same keys, or more exactly, all dicts have at least all the keys present in the first dict.
To make it more robust and handle cases when dicts don't have the same keys:
def dict_zip(*dicts):
all_keys = {k for d in dicts for k in d.keys()}
return {k: [d[k] for d in dicts if k in d] for k in all_keys}
Regarding type hints: not sure, but it might be something based on typing.MutableMapping. But that's Python 3.
EDIT
To add padding for keys which are not present in all dicts:
def dict_zip(*dicts, padding=Nonefillvalue=None):
all_keys = {k for d in dicts for k in d.keys()}
return {k: [d.get(k, paddingfillvalue) for d in dicts] for k in all_keys}
If you have to use Python 2 (if you can, upgrade to Py3 for your own good):
def dict_zip(*dicts, **kwargs):
paddingfillvalue = kwargs.get('padding''fillvalue', None)
all_keys = {k for d in dicts for k in d.keys()}
return {k: [d.get(k, paddingfillvalue) for d in dicts] for k in all_keys}
Notice that you could just do kwargs.get('padding''fillvalue')
and if 'padding''fillvalue'
is not in kwargs
, get
would return None
anyways. But explicit is better than implicit.