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

Python3如何从指定字典列表中提取字段并分别存储

提取字典列表中的字段到对应变量

嘿,这事儿其实挺简单的,用Python的列表推导式或者基础的循环遍历都能轻松实现,我给你两种常用的方案:

方案一:列表推导式(简洁高效)

这是Python里最常用的写法,一行代码就能搞定一个字段的提取,可读性也很强:

# 你的原始字典列表
stock_data = [{'stock_symbol': 'ALT', 'shares_total': 1, 'Price': 12.29}, {'stock_symbol': 'NFLX', 'shares_total': 5, 'Price': 534.5}]

# 提取对应字段到变量
symbols = [item['stock_symbol'] for item in stock_data]
shares = [item['shares_total'] for item in stock_data]
prices = [item['Price'] for item in stock_data]

# 验证结果
print(symbols)  # 输出: ['ALT', 'NFLX']
print(shares)   # 输出: [1, 5]
print(prices)   # 输出: [12.29, 534.5]

方案二:for循环遍历(适合新手理解)

如果你刚接触Python,用基础的for循环一步步来会更直观:

stock_data = [{'stock_symbol': 'ALT', 'shares_total': 1, 'Price': 12.29}, {'stock_symbol': 'NFLX', 'shares_total': 5, 'Price': 534.5}]

# 先初始化空列表
symbols = []
shares = []
prices = []

# 遍历每个字典,提取字段添加到对应列表
for stock in stock_data:
    symbols.append(stock['stock_symbol'])
    shares.append(stock['shares_total'])
    prices.append(stock['Price'])

# 同样可以得到和上面一样的结果
print(symbols)
print(shares)
print(prices)

两种方法最终的效果完全一致,列表推导式更简洁,是典型的Pythonic写法;而for循环更直白,适合刚入门的朋友拆解理解逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:08:28