Python实现按概率为任意深度复杂字典的值追加对应key的~tag标签
完整实现代码
import re import random RE_TAG = re.compile(r".+(~.+)") DLM = '~' tag_occurance = 25 # 追加tag的概率,单位% thisdict = { "Key1~tag": "foo", "Key2": "bar", "Key3~tag": { "Key3.1": "x", "Key3.2~tag": "y" } } def tag(_str): m = RE_TAG.match(_str) if m: return DLM + m[1][1:] # 提取key中的~tag后缀 else: return '' def process_nested_dict(d: dict) -> dict: processed = {} for key, val in d.items(): # 值为字典时递归处理子层级 if isinstance(val, dict): processed[key] = process_nested_dict(val) # 仅字符串类型的值走tag追加逻辑 elif isinstance(val, str): if random.randint(0, 100) < tag_occurance: processed[key] = val + tag(key) else: processed[key] = val # 其他类型值直接保留 else: processed[key] = val return processed # 主流程替换为递归处理 thisdict = process_nested_dict(thisdict) print(thisdict)
核心逻辑说明
- 新增递归处理函数
process_nested_dict,自动遍历所有嵌套层级的字典:- 遍历到值为字典类型时,递归调用自身处理子字典,不会直接尝试字符串拼接
- 仅当值为字符串类型时,才执行概率判断和tag追加逻辑,避免类型报错
- 非字典、非字符串的其他类型值(如数字、列表等)直接保留原样
- 每个字符串值独立触发概率判断,符合原有25%追加的需求设定
- 完全兼容任意深度的嵌套字典结构,和原有tag提取逻辑保持一致
内容的提问来源于stack exchange,提问作者StressedBoi69420
相关产品推荐
相关产品推荐

