使用list / tuple元素创建字典作为关键字 [英] Creating dictionary using list/tuple elements as key

查看:197
本文介绍了使用list / tuple元素创建字典作为关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要生成一个这样的字典:

I need to generate a dictionary like this:

{
  'newEnv': {
     'newProj': {
        'newComp': {
           'instances': [],
           'n_thing': 'newThing'
        }
     }
  }
}

从元组,像这样:(' newEnv','newProj','newComp','newThing'),但只有当它不存在的时候。所以,我试过这个:

from a tuple, like this: ('newEnv','newProj','newComp','newThing') but only if that doesn't already exists. So, I tried this:

myDict = {}
(env,proj,comp,thing) = ('newEnv','newProj','newComp','newThing')

if env not in myDict:
    myDict[env] = {}
if proj not in myDict[env]:
    myDict[env][proj] = {}
if comp not in myDict[env][proj]:
    myDict[env][proj][comp] = {'n_thing': thing, 'instances': []}

这是非常有用的,但不知道如何有效的是,或者我应该这样做。有什么建议么)??

which is pretty much working but not sure how efficient is that or if I should be doing this way at all. Any suggestion(s)??

推荐答案

您可以使用循环(只有前3个键, newThing 不是链中的关键字):

You can use a loop (with just the first 3 keys, newThing is not a key in the chain):

myDict = {}
path = ('newEnv','newProj','newComp')
current = myDict
for key in path:
    current = current.setdefault(key, {})

其中当前最终成为最内部的字典,让您设置 'n_thing''实例'键。

where current ends up as the innermost dictionary, letting you set the 'n_thing' and 'instances' keys on that.

您可以使用 reduce()将其折叠为单行:

You could use reduce() to collapse that into a one-liner:

myDict = {}
path = ('newEnv','newProj','newComp')
reduce(lambda d, k: d.setdefault(k, {}), path, myDict)

reduce 调用返回最内部的字典,所以你可以使用分配您的最终值:

The reduce call returns the innermost dictionary, so you can use that to assign your final value:

myDict = {}
path = ('newEnv','newProj','newComp')
inner = reduce(lambda d, k: d.setdefault(k, {}), path, myDict)
inner.update({'n_thing': 'newThing', 'instances': []})

这篇关于使用list / tuple元素创建字典作为关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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