dic = {"a1": {"a2": {"a3": {"a4": {"a5": {"a6": "6", "a7": "7"}}}}}}
def JSON_Msg_Read_and_Update(Act, JSON, Keys, Data):
# Act 操作 , 'r'读取 , 'u'更新
# JSON 原始数据
# Keys 要查询的Key列表 , ['Key1','Key2,'......]
# Data是需修改的数据 , 读取模式下 Data = None
if Act == "r": # 读取模式
Key = "JSON" # 把Key转化为字符串
for i in Keys: # 循化Keys列表
Key = Key + "['%s']" % i # 把循环字符拼接到Key变量
Result = eval(Key) # 执行字符串表达式并返值
return Result
elif Act == "u": # 更新模式
Key = "JSON"
for i in Keys:
Key = Key + "['%s']" % i
Key = Key + "='%s'" % Data # 把需要修改的内容拼接到Key变量
exec(Key) # 执行字符串代码
Result = JSON
return Result
# 读取模式
print(JSON_Msg_Read_and_Update("r",dic,["a1","a2","a3","a4","a5",],None,))
# 读取模式
print(JSON_Msg_Read_and_Update("u",dic,["a1","a2","a3","a4","a5","a6",],10,))
Python简单访问多层嵌套的字典
最新推荐文章于 2024-08-29 22:39:00 发布