简体   繁体   中英

Create Nested Python Dictionary From Tuple of Keys

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.

You can use reduce 1 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 ...


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM