I'm trying to grab specific values as I iterate through a list of dictionaries that contain nested dictionaries and lists.
This is roughly what my imported json data looks like(simplified). It's a list of dictionaries with nested dictionaries and nested lists.
# What a single dictionary looks like prettified
[{ 'a':'1',
'b':'2',
'c':'3',
'd':{ 'ab':'12',
'cd':'34',
'ef':'56'},
'e':['test', 'list'],
'f':'etc...'
}]
# What the list of dictionaries looks like
dict_list = [{ 'a':'1', 'b':'2', 'c':'3', 'd':{ 'ab':'12','cd':'34', 'ef':'56'}, 'e':['test', 'list'], 'f':'etc...'}, { 'a':'2', 'b':'3', 'c':'4', 'd':{ 'ab':'23','cd':'45', 'ef':'67'}, 'e':['test2', 'list2'], 'f':'etcx2...'},{},........,{}]
This is the code I originally had which only iterates through the list of dictionaries.
for dic in dict_list:
for val in dic.values():
if not isinstance(val, dict):
print(val)
else:
for val2 in val.values():
print (val2)
The print statements in my original code above were there to simply show me what was being pulled from the list of dictionaries. What I wanted to be able to do is declare which values I am looking to grab from the top level and second level dictionaries and lists.
Here is what I am looking for as output as an example.
The value of the first key for each top level dictionary in the list.
top_level_dict_key1 = ['1','2']
All the values for the level 2 dictionaries.
level2_dic = ['12', '34', '56', '23', '45', '67']
Or specific values. In this case the value for the first key in each nested dictionary
level2_dict = ['12', '23']
value for the second key in the nested list
level2_list = ['test', 'test2']
Hopefully this is clear. I'll do my best to clarify if you need me too.