I have multiple python dictionaries in this format, where the top-level keys "3224987", "3590845" etc are not constant they vary per dictionary.
dict1 = {
"3224987": {
"data": {
"skyscrapers":[]
}
},
"3590845":{
"data":{
"bungalows": {
"loc": "leo"
}
}
},
...
"3405901":{
"data":{
"studio":{
"rooms": {}
}
}
}
}
dict2 = {
...,
"784939":{
"data":{
"studio":{
"rooms":{}
}
}
}
}
I am interested in the items within the "studio" key, in the above dictionary i can locate them with dict1["3405901"]["data"]["studio"]
but in other dictionaries it can have a different top level key like dict2["784939"]["data"]["stuido]
.
How can I do this iteratively across many dictionaries (dictX) without worrying about the top-level key?
Thanks
CodePudding user response:
If you have many keys and are not sure if they contain "data" and "studio" you could use try/except:
dict_list = [dict1, dict2...]
for dic in dict_list:
for key in dic:
try:
studio = dic[key]["data"]["studio"]
# do your stuff with studio
except KeyError:
continue