python-3.x - 如何在深度嵌套字典中出现所选键的任何地方用其值替换键:值对?
问题描述
其他问题
这是如何将嵌套字典中的键值对替换为同一键值对中的值的衍生产品?答案仅在一次性嵌套字典中有效。它是通过所有嵌套字典值从循环中衍生出来的吗?我无法解决这个问题。
前:
我有一本嵌套了很多次的字典。
dict_nested = {
"key_":{
"key0a":{
"key1a":{
"sub_key2a":"sub_value2a",
"sub_key2b":"sub_value2b"},
"key1b":"value1b"},
"key0b":{
"key_XYZ":{
"key1a":{
"sub_key2a":"sub_value2a",
"sub_key2b":"sub_value2b"},
"key1b":"value1b"}
}
}
}
后:
结果应如下所示:
dict_nested_new = {
"key_":{
"key0a":{
"sub_key2a":"sub_value2a",
"sub_key2b":"sub_value2b",
"key1b":"value1b"},
"key0b":{
"key_XYZ":{
"sub_key2a":"sub_value2a",
"sub_key2b":"sub_value2b",
"key1b":"value1b"}
}
}
}
迭代 Python 字典时修改它
当我遍历字典的项目以删除/替换时,出现错误
RuntimeError:字典在迭代期间改变了大小
这需要以某种方式避免。
每次在字典中某处出现时,如何将"key1a":SOME_VALUE
键值对替换为其值?
解决方案
据我了解,您希望递归搜索嵌套中的键dict
并提升其值。
这可能不是超级有效,但它应该工作。它也没有真正探索以列表为值的字典,但您的示例数据没有它们,所以我没有实现它。
import copy
import json
def find_replace(this_dict, target_key):
## optional depending on if you care that you mutate this_dict
this_dict = copy.deepcopy(this_dict)
for key in this_dict:
# if the current value is a dict, dive into it
if isinstance(this_dict[key], dict):
this_dict[key] = find_replace(this_dict[key], target_key)
# if the current key is our target merge the values and remove the key
if key == target_key:
this_dict = {**this_dict, **this_dict[key]}
del this_dict[key]
return this_dict
dict_nested = {
"key_":{
"key0a":{
"key1a":{
"sub_key2a":"sub_value2a",
"sub_key2b":"sub_value2b"
},
"key1b":"value1b"
},
"key0b":{
"key_XYZ":{
"key1a":{
"sub_key2a":"sub_value2a",
"sub_key2b":"sub_value2b",
"key1a": {
"sub_key3a":"sub_value3a",
"sub_key3b":"sub_value3b"
},
},
"key1b":"value1b"
}
}
}
}
dict_nested_new = find_replace(dict_nested, "key1a")
print(json.dumps(dict_nested_new, indent=4))
应该给你:
{
"key_": {
"key0a": {
"key1b": "value1b",
"sub_key2a": "sub_value2a",
"sub_key2b": "sub_value2b"
},
"key0b": {
"key_XYZ": {
"key1b": "value1b",
"sub_key2a": "sub_value2a",
"sub_key2b": "sub_value2b",
"sub_key3a": "sub_value3a",
"sub_key3b": "sub_value3b"
}
}
}
}
请注意,我添加了一个附加级别的嵌套,其中包含子嵌套键匹配只是为了显示该场景。其他优化,例如对列表的支持和避免以合理的费用更新未更改的键:-P
推荐阅读
- amazon-web-services - AWS SQS 可见性超时是否对单个消息或每次轮询的所有消息有效
- google-apps-script - 从 Google 通讯录中删除重复或重复的联系人
- url - Google App Script + Google Sheet - 从单元格中获取 URL(链接到单独的工作表)并从链接的工作表中拉入工作表选项卡
- python - Python - 数据框 - Matplotly - KeyError:“[列]中没有[Int64Index / Datetime ...]
- snowflake-cloud-data-platform - 更好地控制雪花中的表锁定
- javascript - 拉动刷新奇怪的行为
- ruby-on-rails - 是否可以创建一个在创建新的 Rails 应用程序时执行的脚手架?
- angular - Angular 开始监听 AppData/Local/Programs/Git
- kubernetes-helm - Helm:coalesce.go:196:警告:不能用非表覆盖表用于 env(map [])
- java - 从后台任务将日志保存到文件系统