Python中文
首页
教程
问答
标签
搜索
登录
注册
从嵌套字典中删除基于条件的子CT
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我有一个嵌套字典,包含“密度”和“温度”的(子)dicts。结构如下:</p> <pre><code>profiles_dict = { "density": { "elements": [ { "layers": [ { "top": 54.0, "bottom": 3.75, "value": 218.9 } ] } ], "type": "density" }, "temperature": { "elements": [ { "layers": [] } ], "type": "temperature" } } </code></pre> <p>正如在temperature子ct中可以看到的,“layers”键包含一个空列表作为值。我的目标是创建一个循环/函数来删除字典<code>{"layers": []}</code></p> <p>结果应该如下所示:</p> <pre><code>profiles_dict_new = { "density": { "elements": [ { "layers": [ { "top": 54.0, "bottom": 3.75, "value": 218.9 } ] } ], "type": "density" }, "temperature": { "elements": [ ], "type": "temperature" } } </code></pre> <hr/> <p>我尝试了以下方法:</p> <pre><code>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) </code></pre> <p>通过这个循环,我可以访问<code>{'layers': []}</code>,但是我不知道如何正确地将它从dictionray中删除</p> <p>第二种方法基于Ajax1234解决方案(<a href="https://stackoverflow.com/questions/48017281/deleting-items-based-on-keys-in-nested-dictionaries-in-python">Deleting Items based on Keys in nested Dictionaries in python</a>)</p> <pre><code>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) </code></pre> <p>这给了我以下错误:</p> <pre><code>--------------------------------------------------------------------------- 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' </code></pre> <p>对于所介绍的任何一种方法,我们都非常感谢您的帮助</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>而不是删除分配空列表</p> <p>您可以尝试以下代码:</p> <pre><code>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 == []: v1[k2] = [] </code></pre>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
将Pandas数据帧转换为PyTorch张量?
4 回答
将Pandas数据帧转换为scipy稀疏矩阵
8 回答
将Pandas数据帧转换为Spark Datafram时出现问题
8 回答
将pandas数据帧转换为spark DataFram时出错
7 回答
将Pandas数据帧转换为spark datafram时收到错误
2 回答
将Pandas数据帧转换为Spark数据帧
1 回答
将Pandas数据帧转换为Tensorflow数据
7 回答
将Pandas数据帧转换为tkinter obj
4 回答
将pandas数据帧转换为XML
2 回答
将Pandas数据帧转换为值sql语句
10 回答
将pandas数据帧转换为元组
2 回答
将pandas数据帧转换为元组列表
9 回答
将pandas数据帧转换为元组列表并删除所有pandas数据类型
4 回答
将pandas数据帧转换为具有头和数据类型的numpy数组
8 回答
将pandas数据帧转换为内存中的拼花地板,并将其加载到Python中的Hadoop中
4 回答
将pandas数据帧转换为内存中类似文件的对象?
3 回答
将Pandas数据帧转换为内存功能(&F)
9 回答
将pandas数据帧转换为列表列表
1 回答
将pandas数据帧转换为列表列表以输入到RNN
2 回答
将Pandas数据帧转换为单行DataFram
7 回答