将变量分配给“键”:基于另一个键中的值的值

问题描述 投票:0回答:1

我正在浏览字典:

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调用,该API返回返回另一组数据,这些数据将被写入.csv文件。到目前为止一切顺利。

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

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

python python-3.x
1个回答
0
投票

所以可能是这样的:

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 
© www.soinside.com 2019 - 2024. All rights reserved.