Python从LDIF文件构建字典时如何为同一key存储多个属性值
问题本质
- 自实现LDIF解析逻辑的固有缺陷:逐行读取属性键值对后,直接以属性名为键写入普通字典,遇到重复同名属性时直接触发值覆盖,最终每个键仅能保留最后一次读取到的单值,无法适配多值属性存储需求
- 目标输出为字典数组结构,每个数组元素对应LDIF中一个DN实体条目,所有同名属性的多值需要聚合为统一格式的存储值
核心适配逻辑
要解决多值覆盖问题,只需要在写入字典值时增加键存在性判断分支:
- 逐行读取LDIF内容时,先跳过空行、注释行、占位分隔行
- 拆分每行的
属性名:属性值片段后,将属性名统一转为小写(符合LDIF协议属性名大小写不敏感的规则,避免同属性因大小写差异被识别为不同键) - 对拆分后的属性键做分支判断:
- 键不存在:直接将当前属性值存入字典
- 键已存在:将新的属性值与原有值聚合,最终形成逗号分隔的多值字符串,匹配目标输出格式
- 遇到条目分隔时(空行),将填充完成的字典存入结果列表,重置空字典准备解析下一个独立DN条目
可直接运行的核心代码实现
def parse_ldif(ldif_content): result = [] current_item = {} for line in ldif_content.splitlines(): stripped_line = line.strip() # 过滤无意义行 if not stripped_line or stripped_line.startswith('#') or stripped_line.startswith('......'): # 空行作为条目分隔符 if not stripped_line and current_item: result.append(current_item) current_item = {} continue # 拆分键值对 if ':' in stripped_line: key_part, value_part = stripped_line.split(':', 1) norm_key = key_part.strip().lower() norm_value = value_part.strip() # 多值适配判断 if norm_key not in current_item: current_item[norm_key] = norm_value else: current_item[norm_key] = f"{current_item[norm_key]},{norm_value}" # 处理文件末尾无空行分隔的最后一个条目 if current_item: result.append(current_item) return result
针对样例LDIF的输出校验
使用上述逻辑解析给出的测试LDIF内容,最终返回的Myldif_dic结构与预期完全一致:
Myldif_dic = parse_ldif( """ Dn: sample,dc=sample,dc=com Objectclass: top Objectclass: organizational Cn: sample Address: 123 Address: 345 .......................... """ ) # 实际输出结构为: # [ # { # 'dn': 'sample,dc=sample,dc=com', # 'objectclass': 'top,organizational', # 'cn': 'sample', # 'address': '123,345' # } # ]
灵活调整提示:如果后续业务需要单独拆分每个多值做处理,只需把多值适配段的聚合逻辑改为列表存储——检测到键已存在时直接执行
current_item[norm_key].append(norm_value)即可,不需要改动其他解析流程。
内容的提问来源于stack exchange,提问作者Shali
相关产品推荐
相关产品推荐

