3

I have an iterable of keys like ('a', 'b', 'c') that I want to correspond to an entry in a dictionary I am building. I am looking for a one-linerish way to build this dictionary from multiple tuples.

Input:

keys = ('a', 'b', 'c') value = 'bar' 

Output:

{'a': {'b': {'c': 'bar'}}} 

I have been trying things using defaultdict, but haven't really gotten the grasp of it. The one-liner requirement is pretty soft, but I was hoping to get a really small footprint for this.

1 Answer 1

5

You can use reduce1 here:

reduce(lambda x, y: {y: x}, keys[::-1], value) 

Or, use the iterator returned by reversed:

reduce(lambda x, y: {y: x}, reversed(keys), value) 



A lot of people might not like this too much. Unless you're really into functional programming in python, this is a bit opaque. A simpler solution takes only 3 lines:

>>> keys = ('a', 'b', 'c') >>> value = 'bar' >>> for c in reversed(keys): ... value = {c: value} ... >>> value {'a': {'b': {'c': 'bar'}}} 

and doesn't rely on any slightly obscure builtin functions.

FWIW, I'm not sure which version I prefer ...


1functools.reduce in python3.x which also exists in python2.6+ to ease py3k transitions IIRC

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.