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

Python 3.9:将含id列表的字典列表转换为指定格式字典

解决方案

可以通过嵌套循环实现需求:先遍历原列表中的每个字典,再针对每个字典里的id列表逐个处理,生成目标键值对并添加到结果字典中。

代码实现

variables = [
    {'id': ['alpha'], 'ip': '10.10.10.10', 'name': 'primary'},
    {'id': ['beta', 'gamma'], 'ip': '10.10.10.20', 'name': 'secondary'}
]

result = {}
for item in variables:
    # 取出当前字典的id列表、ip和name值
    ids = item['id']
    ip_val = item['ip']
    name_val = item['name']
    # 遍历每个id,生成对应的键值对
    for current_id in ids:
        result[f"{current_id}.ip"] = ip_val
        result[f"{current_id}.name"] = name_val

print(result)

输出结果

运行后会得到你需要的格式:

{
    'alpha.ip': '10.10.10.10',
    'alpha.name': 'primary',
    'beta.ip': '10.10.10.20',
    'beta.name': 'secondary',
    'gamma.ip': '10.10.10.20',
    'gamma.name': 'secondary'
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 11:04:53