【发布时间】:2021-07-15 14:36:40
【问题描述】:
我有一个嵌套字典,其中包含“密度”和“温度”的(子)字典。这是结构:
profiles_dict =
{
"density": {
"elements": [
{
"layers": [
{
"top": 54.0,
"bottom": 3.75,
"value": 218.9
}
]
}
],
"type": "density"
},
"temperature": {
"elements": [
{
"layers": []
}
],
"type": "temperature"
}
}
正如在温度细分中看到的那样,“层”键包含一个空列表作为值。我的目标是创建一个循环/函数来删除字典{"layers": []}。
结果应该是这样的:
profiles_dict_new =
{
"density": {
"elements": [
{
"layers": [
{
"top": 54.0,
"bottom": 3.75,
"value": 218.9
}
]
}
],
"type": "density"
},
"temperature": {
"elements": [
],
"type": "temperature"
}
}
我尝试了以下方法:
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)
通过这个循环,我可以访问{'layers': []},但是我不知道如何从字典中正确删除它。
第二种方式是基于Ajax1234的方案(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)
这给了我以下错误:
---------------------------------------------------------------------------
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'
感谢您对所提出的任何一种方法的帮助。
【问题讨论】:
标签: python loops dictionary nested