Saturday 5 December 2009

Python return dictifier

I wrote this the other week, and thought it was cute enough to share:


def _dictify(keys, result):
if len(keys) == 1:
return { keys[0]: result }
return dict(zip(keys, result))

def return_dict(keys):
keys = keys.split()
def decorator(f):
def g(*_, **__):
return _dictify(keys, f(*_, **__))
return g
return decorator

Use it as follows:

>>> @return_dict('foo bar baz')
... def f():
... return 1, 2, 3
...
>>> f()
{'baz': 3, 'foo': 1, 'bar': 2}

Enjoy!

No comments: