Python 创建通过两个嵌套循环和一个JSON输出进行迭代的dict

Python 创建通过两个嵌套循环和一个JSON输出进行迭代的dict,python,json,list,dictionary,Python,Json,List,Dictionary,我需要从两个列表(env和coms)和一个JSON输出(每个用于每个env-com组合)中创建一个字典,如下面的脚本所示。我想要的结果字典应该类似于: { "live-business-data-infrastructure": { "component": "traveldb", "environment": "test" }, { .... } } 这只是我用原始脚本制作的一个示例,用于演示我所追求的: #!/usr/bin/en

我需要从两个列表(env和coms)和一个JSON输出(每个用于每个env-com组合)中创建一个字典,如下面的脚本所示。我想要的结果字典应该类似于:

{
    "live-business-data-infrastructure": {
        "component": "traveldb", 
        "environment": "test"
    }, 
    { .... }
}
这只是我用原始脚本制作的一个示例,用于演示我所追求的:

#!/usr/bin/env python

import json 
envs = [ 'test','live', ]  ## originallt: [ 'test','live',... ]
coms = [ 'traveldb' ]      ## originally: [ 'traveldb','weatherbot',... ]
test_traveldb_stks = [ {
                          "main_stack": 'false',
                          "name": "test-business-data-resources"
                        },
                        {
                          "main_stack": 'true',
                          "name": "test-business-data-infrastructure"
                        }
                      ]
live_traveldb_stks = [ {
                          "main_stack": 'false',
                          "name": "live-business-data-resources"
                        },
                        {
                          "main_stack": 'true',
                          "name": "live-business-data-infrastructure"
                        }
                      ]

aList = []; sDict = {}

for env in envs:
    for com in coms:
        aList.extend([ zz['name'] for zz in eval(env+'_'+com+'_stks') ])
        sDict[aList[-1]] = { 'component':com, 'environment':env }

#print(aList)
print(json.dumps(sDict, sort_keys=True, indent=4))

这非常有效,但由于脚本中的
sDict[aList[-1]]
位而丢失了一些数据,但无法完全理解如何迭代两个嵌套循环并使用JSON映射以获得所需的dict。有什么建议吗?如果我没有说清楚,请告诉我。干杯

我想你很接近了,但是为什么你只选了
列表中的最后一项呢?通过使用
extend
而不是
append
可以获得

aList = [olditem, olditem, newitem, newitem]
                                  # ^ aList[0]
不是

此外,您还需要遍历这些项。尝试:

aList = []
sDict = {}
for com in coms:
    for env in envs:
        for d in eval("{0}_{1}_stks".format(env, com)):
            aList.append(d["name"]) # add name from d to end of aList
            sDict[d["name"]] = {'component': com, 'environment': env}

请注意,如果您只是用它来填充
sDict
而没有进一步的用途,则可以省略
aList=[]
aList.append(…)

我喜欢这样。不过有两个问题:
aList.append(d[“name”])
在这里有什么用?而我
“{}{}{}{}{u stks”对我不起作用,我不得不用“{0}{1}{u stks”。目前正在我的原始脚本中进行测试。干杯
{}
/
{0}
问题是Python2.x和3.x的问题。我已经更新了我的答案和评论。
aList = []
sDict = {}
for com in coms:
    for env in envs:
        for d in eval("{0}_{1}_stks".format(env, com)):
            aList.append(d["name"]) # add name from d to end of aList
            sDict[d["name"]] = {'component': com, 'environment': env}