飞行中生成字典键 [英] Generating dictionary keys on the fly
本文介绍了飞行中生成字典键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用深层嵌套的python dicts,我希望能够在这样的数据结构中分配值:
mydict [key] [subkey] [subkey2] =value
而无需检查mydict [key]等实际设置为一个dict,例如使用
如果不是密码mydict:mydict [key] = {}
/ pre>
创建子例句应该是即时发生的。什么是最优雅的方式来允许等同的东西 - 也许在标准的
< type'dict'>
中使用装饰器?解决方案
class D(dict):
def __missing __(self,key):
self [key] = D()
return self [key]
d = D()
d ['a'] ['b'] ['c'] = 3
Working with deeply nested python dicts, I would like to be able to assign values in such a data structure like this:
mydict[key][subkey][subkey2]="value"
without having to check that mydict[key] etc. are actually set to be a dict, e.g. using
if not key in mydict: mydict[key]={}
The creation of subdictionaries should happen on the fly. What is the most elegant way to allow something equivalent - maybe using decorators on the standard
<type 'dict'>
?解决方案class D(dict): def __missing__(self, key): self[key] = D() return self[key] d = D() d['a']['b']['c'] = 3
这篇关于飞行中生成字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文