如何使用Python从条件字符串中提取键值对生成目标字典
实现方案
核心用正则匹配所有字段 == '值'的键值对组合,直接转为字典即可,代码实现如下:
import re def parse_condition_to_dict(condition_str: str) -> dict: # 正则规则:匹配字段名(支持字母、数字、下划线、点)、等于号、单引号包裹的取值 match_pattern = r"([\w.]+)\s*==\s*'([^']+)'" # 提取所有匹配的键值对元组,直接转为字典 result = re.findall(match_pattern, condition_str) return dict(result)
测试效果
代入示例字符串测试:
test1 = "if rpd.col_A == 'Type A'" test2 = "if (rpd.col_A == 'Type B') AND (rpd_dev == 'Other') AND (rpd_form == 'Other')" test1_dict = parse_condition_to_dict(test1) test2_dict = parse_condition_to_dict(test2) print(test1_dict) # 输出:{'rpd.col_A': 'Type A'} print(test2_dict) # 输出:{'rpd.col_A': 'Type B', 'rpd_dev': 'Other', 'rpd_form': 'Other'}
说明
当前实现适配给定的条件字符串格式:所有判断规则为字段 == '单引号字符串'、用AND连接的场景,如果后续有其他比较规则、取值格式可以调整正则规则适配。
内容的提问来源于stack exchange,提问作者Fazli
相关产品推荐
相关产品推荐

