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

Python如何将字典列表中所有record_id值统一转为列表类型

Python 字典列表record_id字段统一转列表实现方案

核心逻辑

遍历列表内的所有字典,对每个字典的record_id字段做类型判断:

  • 已为列表类型的字段直接保留
  • 非列表类型的字段,包装为单元素列表即可,可根据需求选择是否做类型转换(你示例中需要将数值转为字符串,因此代码中加了str()处理)

实现代码

原地修改原列表版本

直接修改原有列表内的字典,不需要额外占用内存存储新列表:

list_of_dict = [
    {'f_text': 'sample', 'symbol': '*', 'f_id': 246, 'record_id': ['4680', '4679'], 'flag': 'N'},
    {'f_text': 'other text', 'symbol': '!#', 'f_id': 247, 'record_id': 4678, 'flag': 'N'}
]

for item in list_of_dict:
    val = item['record_id']
    if not isinstance(val, list):
        # 不需要转字符串的话直接写 item['record_id'] = [val] 即可
        item['record_id'] = [str(val)]

生成新列表版本(不修改原数据)

如果需要保留原有列表的数据,用列表推导式生成新的字典列表即可:

list_of_dict = [
    {'f_text': 'sample', 'symbol': '*', 'f_id': 246, 'record_id': ['4680', '4679'], 'flag': 'N'},
    {'f_text': 'other text', 'symbol': '!#', 'f_id': 247, 'record_id': 4678, 'flag': 'N'}
]

new_list = [
    {**item, 'record_id': item['record_id'] if isinstance(item['record_id'], list) else [str(item['record_id'])]}
    for item in list_of_dict
]

两种方案执行后都能得到你给出的预期输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 08:06:05