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

如何将字典列表转换为元组列表?Python新手求助

字典列表转指定顺序元组列表的解决方法

你的代码在Python 3.7及以上版本其实可以运行,但存在两个潜在问题:一是Python 3.7之前的字典是无序的,dic.values()返回的顺序无法保证和你预期的name、gender、marks一致;二是依赖字典插入顺序不够可靠,后续字典结构变化时结果会出错。

更稳妥的方式是明确指定要提取的键的顺序,以下是两种实现方式:

方式一:循环遍历构建

lst = [{'name': 'John', 'gender': 'Male', 'marks': [20,30,40]}, 
       {'name': 'Lynn', 'gender': 'Female', 'marks': [20,30,40,50,60]}]

new_list = []
for dic in lst:
    # 按name、gender、marks的顺序提取值并转为元组
    new_tuple = (dic['name'], dic['gender'], dic['marks'])
    new_list.append(new_tuple)

print(new_list)

方式二:列表推导式(更简洁)

lst = [{'name': 'John', 'gender': 'Male', 'marks': [20,30,40]}, 
       {'name': 'Lynn', 'gender': 'Female', 'marks': [20,30,40,50,60]}]

new_list = [(d['name'], d['gender'], d['marks']) for d in lst]
print(new_list)

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

[('John', 'Male', [20, 30, 40]), ('Lynn', 'Female', [20, 30, 40, 50, 60])]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 19:43:14