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

如何转换Python字典中各列表类型值的首个元素为字符串类型

实现方案

你可以通过遍历字典的键值对完成转换,为了避免索引异常,建议先判断值为列表且列表非空再做修改:

方法1:原地修改原字典

直接在原始字典上修改,内存开销更小:

dictionary = {"first":[1, 2, 3], 
              "second":[4, 5, 6, 7, 8]}

for k, v in dictionary.items():
    if isinstance(v, list) and len(v) > 0:
        v[0] = str(v[0])

print(dictionary)
# 输出:{'first': ['1', 2, 3], 'second': ['4', 5, 6, 7, 8]}

方法2:生成新字典(不修改原始数据)

如果需要保留原始字典不变,可以用字典推导式生成新字典:

dictionary = {"first":[1, 2, 3], 
              "second":[4, 5, 6, 7, 8]}

new_dictionary = {
    k: [str(v[0])] + v[1:] if isinstance(v, list) and len(v) > 0 else v
    for k, v in dictionary.items()
}

print(new_dictionary)
# 输出:{'first': ['1', 2, 3], 'second': ['4', 5, 6, 7, 8]}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 13:15:04