I have a nested dictionary containing (sub)dicts for "density" and "temperature". This is the structure:
profiles_dict =
{
"density": {
"elements": [
{
"layers": [
{
"top": 54.0,
"bottom": 3.75,
"value": 218.9
}
]
}
],
"type": "density"
},
"temperature": {
"elements": [
{
"layers": []
}
],
"type": "temperature"
}
}
As one can see in the temperature subdict, the "layers" key contains an empty list as value. My goal is to create a loop/function that removes the dictionary {"layers": []}.
The result should look like this:
profiles_dict_new =
{
"density": {
"elements": [
{
"layers": [
{
"top": 54.0,
"bottom": 3.75,
"value": 218.9
}
]
}
],
"type": "density"
},
"temperature": {
"elements": [
],
"type": "temperature"
}
}
I have tried the following:
for k1, v1 in profiles_dict.items():
for k2, v2 in v1.items():
if type(v2) != list:
continue
for i in v2:
for k3, v3 in i.items():
if v3 == []:
del(i)
With this loop, I can access {'layers': []}, however I don't know how to properly remove it form the dictionray.
The second approach is based on Ajax1234 solution (Deleting Items based on Keys in nested Dictionaries in python)
profiles_dict_new = {d:{e:[{l:v for l, v in e.items() if v != []}]} for d, e in profiles_dict.items()}
print(profiles_dict_new)
This gives me the following error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-11-126f19ab7afd> in <module>
----> 1 profiles_dict_new = {d:{e:[{l:v for l, v in e.items() if v != []}]} for d, e in profiles_dict.items()}
2 print(profiles_dict_new)
<ipython-input-11-126f19ab7afd> in <dictcomp>(.0)
----> 1 profiles_dict_new = {d:{e:[{l:v for l, v in e.items() if v != []}]} for d, e in profiles_dict.items()}
2 print(profiles_dict_new)
TypeError: unhashable type: 'dict'
Help is appreciated for either of the presented approaches.