访问嵌套字典,它是关键Python的值

我将字典嵌套在一个类似于以下内容的列表中:

data = [{'ID-1010': {'Id': '0060', 'ID18__c': 'abc'}},
{'ID-1020': {'Id': '0060', 'ID18__c': 'abd'}},
{'ID-1030': {'Id': '0060', 'ID18__c': 'abf'}}]

我需要遍历数据,获取ID18__c键的值并将其保存在变量中。我尝试了以下方法:

for index, my_dict in enumerate(data):
    my_var = data[{key}['ID18__c']
    print(my_var)

键未定义,我如何从print语句访问所需的输出“ ID18__c”的值是:

abc
abd
abf
评论
  • 时光逆转
    时光逆转 回复

    key is indeed not defined, because you never created such variable.

    您可以遍历数组,然后使对象循环获得的每个对象的键:

    for obj in data:
        for obj_key in obj:
            print(obj[obj_key]['ID18__c'])
    
  • ha
    ha 回复

    Your key is not defined, because where are you creating key? Also data[{key}['ID18__c'] won't work. That looks like invalid syntax. Also no need to use enumerate(), since you don't need any indices to do this.

    What you need to do is loop over each dictionary inside the list, then loop over the values inside the dictionary, which is a dictionary as well. Then you can call the 'ID18__c' key.

    for dic in data:
        for v in dic.values():
            print(v['ID18__c'])
    

    我们也可以遍历键:

    for dic in data:
        for k in dic:
            print(dic[k]['ID18__c'])
    

    输出:

    abc
    abd
    abf