如何使用迭代器访问多级dict python?

时间:2018-09-10 07:37:01

标签: python-3.x dictionary iterator

我有这个dict / json:

data={
"paraview": {
    "3.5": {
        "image": "/data/singularity/containers/paraview_5.5.2.simg",
        "recipe": "/data/singularity/YAJE/yaje/paraview/Singularity.5.5.2",
        "source": "packet"
    },
    "5.5.2": {
        "image": "/data/singularity/containers/paraview_5.5.2.simg",
        "recipe": "/data/singularity/YAJE/yaje/paraview/Singularity.5.5.2",
        "source": "packet"
    }
  }
}

我可以通过以下方式找到一个值:

app ="paraview"
version= "3.5"

if app in data:
   if version in data[app]:
       print("ubucacion: {}".format(data[app][version]['image']))

输出:

ubucacion: /data/singularity/containers/paraview_5.5.2.simg

但是,对于很大的字典,我该如何使用iteratos?

1 个答案:

答案 0 :(得分:0)

你的意思是:

for i in [(app,version), (app,version)]:
    if i[0] in data and i[1] in data[i[0]]: # secondhalf of and statement won't run if first half is false
        print("ubucacion: {}".format(data[i[0]][i[1]]['image']))