python - 如何展平嵌套的字典并在碰撞时使用内部值
问题描述
问题
对于以下字典:
{'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}
我想创建一个没有remove_me
orworld
键的新字典。
编辑更新:
总而言之,我想做以下事情:
如果项目的值是嵌套字典。使用内部结果更新新字典,同时从主字典中删除当前键值。
如果项目的值不是嵌套字典,则使用键值更新新字典。
接受的答案涵盖了这一点。
我尝试了什么?
{k:v for (k,v) in d.items() if not k == 'remove_me'}
产量:
{'id': 1, 'label': 'hello'}
不完全是我需要的,因为我正在删除嵌套的字典。
期望的输出:
{'id': 1, 'label': 'hello','keep_me': 52}
解决方案
dico = {'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}
# Just what you have done
new_dico = {k:v for (k,v) in dico.items() if not k == 'remove_me'}
# Plus this line
new_dico.update(dico['remove_me']['world'])
print(new_dico)
# {'id': 1, 'label': 'hello', 'keep_me': 52}
受我在此处阅读的内容的启发,主 dict 的 flatten 函数,无论您的 key-dict 的深度是什么:
dico = {'id': 1, 'label': 'hello', 'remove_me': {'world': {'keep_me': 52}}}
def dFlatten(dico, d = {}):
for k, v in dico.items():
if isinstance(v, dict):
dFlatten(v)
else:
d[k] = v
return d
dico = dFlatten(dico)
print(dico)
# {'id': 1, 'label': 'hello', 'keep_me': 52}
例如更深的 dico :
dico2 = {'id': 1, 'label': 'hello', 'stuff1': {'stuff2': {'remove_me': {'world': {'keep_me': 52}}}}}
dico2 = dFlatten(dico2)
print(dico2)
# {'id': 1, 'label': 'hello', 'keep_me': 52}
具有多个具有相同 dFlatten 功能的深键
dico3 = {'id': 1, 'label': 'hello', 'deep': {'L1': {'L2': 52}}, 'remove_me': {'world': {'keep_me': 52}}}
dico3 = dFlatten(dico3)
print(dico3)
# {'id': 1, 'label': 'hello', 'keep_me': 52, 'L2': 52}
推荐阅读
- java - 字符串中的 NullPointerException
- r - 在 R 中的 shapefile 上绘制空间数据集时,如何绘制空间数据集的坐标?
- python - 如何为自己更改 setter 和 getter 以便能够在 python 中处理类和组合
- java - 错误“未为 User 类型定义带有 DefaultPasswordEncoder() 的方法”Spring Boot 密码
- javascript - 再次使用组件做出反应
- xslt - 基于 xslt 中的一个元素将 xml 记录与所需的子元素分组
- ios - 将 iOS 应用上传到我的个人 Apple 开发者帐户
- visual-foxpro - 这个函数在 Visual Foxpro 中有什么作用?
- sql-server - 查询仅更改sql server中的最后一条记录值
- java - 如何在 Android Studio 中更新分数和星星?