Reputation: 1530
I have nested dictionaries in a list that looks like the following:
data = [{'ID-1010': {'Id': '0060', 'ID18__c': 'abc'}},
{'ID-1020': {'Id': '0060', 'ID18__c': 'abd'}},
{'ID-1030': {'Id': '0060', 'ID18__c': 'abf'}}]
I need to loop through the data, grab ID18__c key's value and save it in a variable. I have tried the following:
for index, my_dict in enumerate(data):
my_var = data[{key}['ID18__c']
print(my_var)
Key is not defined, how would I access the value of 'ID18__c' my desired output from print statement is:
abc
abd
abf
Upvotes: 1
Views: 79
Reputation: 62536
key
is indeed not defined, because you never created such variable.
You can loop over the array, and then loop object the keys of each object you got:
for obj in data:
for obj_key in obj:
print(obj[obj_key]['ID18__c'])
Upvotes: 3
Reputation: 26315
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'])
We could also just loop over the keys:
for dic in data:
for k in dic:
print(dic[k]['ID18__c'])
Output:
abc
abd
abf
Upvotes: 2