首页 > 解决方案 > 将变量分配给“键”:基于另一个键中的值的值

问题描述

我正在遍历字典:

d = {'clubs': [{'id': 30, 'club_name': 'One'}, 
           {'id': 33, 'club_name': 'Two'}]
    }

并将键“id”的值分配给变量 x。

for x in d['clubs']:
        x = x['id']
        print(x)

然后我将“id”传递给 API 调用,该调用返回另一组数据,这些数据将写入 .csv 文件。到目前为止,一切都很好。

当我循环遍历时,我想将另一个变量设置为同一记录的“club_name”键中的值,以便我可以在命名输出文件时使用它。

任何方向将不胜感激。谢谢。

标签: pythonpython-3.x

解决方案


所以可能是这样的:

for k,v in d.items():
   if k == "clubs":
      for key,val in d[k].items():
        if key == "club_name":
          getClubVals = d[key]
          # this should be some guidance with what you need, you will get the 
          # values for that specific key i.e "club_name"
          # you can append the values or some do some sort of return with the values 

推荐阅读