设置嵌套的dict值并创建中间密钥 [英] Set nested dict value and create intermediate keys

查看:153
本文介绍了设置嵌套的dict值并创建中间密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得我最近看到了一个办法。说我有一个空的dict,我想在一个空的dict里面的一个嵌套的dict里设置一个值,但是显然,嵌套的dict还没有被创建。是否有1行方式来创建中间键?这是我想做的:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆