You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按公共名称分组Python字典中的键值对

字典分组解决方案

可以通过遍历原字典的键值对,拆分键的前缀与属性名,再按前缀分组整理成目标结构,代码实现如下:

my_dict = {
 'Admin.Email': 'admin@domein.nl',
 'Admin.Name': 'Admin Account',
 'Admin.Phone': '+31 6 12345678',
 'Admin.RipeID': 'nan',
 'Loc.Address': 'Testraat 100',
 'Loc.Country': 'Nederland',
 'Loc.Place': 'Plaatsnaam',
 'Loc.Postalcode': '1234AB',
 'Org.Address': 'Testraat 100',
 'Org.Country': 'Nederland',
 'Org.Email': 'email@domein.nl',
 'Org.Name': 'Bedrijfsnaam',
 'Org.Place': 'Plaatsnaam',
 'Org.Postalcode': '1234AB',
 'Org.RipeID': 'nan',
 'Tech.Email': 'tech@domein.nl',
 'Tech.Name': 'Tech Account',
 'Tech.Phone': '+31 6 87654321',
 'Tech.RipeID': 'nan',
 'Technische contactpersoon': 'nan'
}

new_dict = {'attributes': {}}

for key, value in my_dict.items():
    # 拆分键为组名和属性名,仅按第一个点分割
    parts = key.split('.', 1)
    if len(parts) == 2:
        group, attr = parts
        # 组名和属性名统一转小写
        group_lower = group.lower()
        attr_lower = attr.lower()
        
        # 若组不存在则初始化空列表
        if group_lower not in new_dict['attributes']:
            new_dict['attributes'][group_lower] = []
        
        # 将属性信息添加到对应组
        new_dict['attributes'][group_lower].append({
            'name': attr_lower,
            'value': value
        })

print(new_dict)

代码说明

  • 用split('.', 1)拆分键,确保仅分割前缀与属性名,避免属性名含点时出错
  • 统一将组名、属性名转为小写,匹配目标结构的格式要求
  • 自动创建不存在的组,再将属性信息以字典形式追加到对应组的列表中
  • 无点分隔的键(如Technische contactpersoon)因无法拆分明确组名会被跳过,需处理可额外添加逻辑

内容的提问来源于stack exchange,提问作者Beeelze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 10:13:13