替换嵌套列表和字典中的项目 [英] Replace items in a dict of nested list and dicts
本文介绍了替换嵌套列表和字典中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有什么解决方案可以用嵌套列表的 dict
中的特定值替换项目,而python中的dicts是否可用?
Is there any solution to replace items with a specific value in a dict
of nested list and dicts in python ?
例如:
输入:
item_to_be_replaced = 'a'
replaced_with = 'z'
di = {"a": "A", "b": "B", "c": [2, 4, 6, {"a": "A", "b": "B"}], "d": {"a": [2, 4, 6], "b": [5, 2, 1]}}
输出:
{"z": "A", "b": "B", "c": [2, 4, 6, {"z": "A", "b": "B"}], "d": {"z": [2, 4, 6], "b": [5, 2, 1]}}
解决这个问题的最佳方法是什么?
which is the most optimal way to solve this problem ?
推荐答案
我不认为这是最好的选择,但是当我看到这个时,我就想到了这个答案:
I dont thing its the best option, but when i saw this i thought about this answer:
import json
json.loads(json.dumps(di).replace(f'"{item_to_be_replaced}"', f'"{replaced_with}"'))
简单地转换为字符串,替换我需要替换的东西,然后返回到 dict
Simple convert into string, replace the thing that i need to replace, and back to dict
这篇关于替换嵌套列表和字典中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文