设置嵌套的dict值并创建中间密钥 [英] Set nested dict value and create intermediate keys
问题描述
mydict = {}
mydict ['foo'] ['bar' ] ['foobar'] = 25
如果你执行这个代码,你会得到一个KeyError异常富。有没有创建中间密钥的功能?
谢谢。
从集合导入defaultdict
recursivedict = lambda:defaultdict(recursivedict)
mydict = recursivedict()
当您访问 mydict ['foo']
时,它设置 mydict ['foo' ]
到另一个 recursivedict
。它实际上将为 mydict ['foo'] ['bar'] ['foobar']
构建一个 recursivedict
但是,通过将它分配给 25
,然后它将被抛出。
I feel like I saw a way to do this recently. Say I've got an empty dict and I want to set a value in a nested dict inside that empty dict, but obviously that nested dict hasn't been created yet. Is there a 1-line way to create the intermediate keys? This is what I want to do:
mydict = {}
mydict['foo']['bar']['foobar'] = 25
If you execute this code you'll get a KeyError exception for 'foo'. Is there a function to create intermediate keys?
Thanks.
from collections import defaultdict
recursivedict = lambda: defaultdict(recursivedict)
mydict = recursivedict()
When you access mydict['foo']
, it sets mydict['foo']
to another recursivedict
. It'll actually construct a recursivedict
for mydict['foo']['bar']['foobar']
as well, but then it'll get thrown out by assigning that to 25
.
这篇关于设置嵌套的dict值并创建中间密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!