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

如何从列表中的字典提取含'symbol'键的对应值

提取列表字典中的symbol字段值

针对你的数据集,以下是几种提取所有symbol对应值的方法:

1. 列表推导式(简洁高效写法)

这是Python中常用的简洁实现,同时加入键存在判断避免报错:

# 定义你的数据集
data = [
    {'symbol': 'BTCUSDT', 'initialMargin': '2.68109529', 'maintMargin': '0.13405476', 'unrealizedProfit': '-0.07952355', 'positionInitialMargin': '2.68109529', 'openOrderInitialMargin': '0', 'leverage': '5', 'isolated': False, 'entryPrice': '0.899', 'maxNotional': '250000', 'positionSide': 'BOTH', 'positionAmt': '15.0', 'notional': '13.40547645', 'isolatedWallet': '0', 'updateTime': '1676641281047', 'bidNotional': '0', 'askNotional': '0'},
    {'symbol': 'EOSUSDT', 'initialMargin': '3.22845093', 'maintMargin': '0.08071127', 'unrealizedProfit': '-0.06225465', 'positionInitialMargin': '3.22845093', 'openOrderInitialMargin': '0', 'leverage': '5', 'isolated': False, 'entryPrice': '1.072', 'maxNotional': '2000000', 'positionSide': 'BOTH', 'positionAmt': '-15.0', 'notional': '-16.14225465', 'isolatedWallet': '0', 'updateTime': '1676641497608', 'bidNotional': '0', 'askNotional': '0'}
]

# 提取所有symbol值
symbols = [item['symbol'] for item in data if 'symbol' in item]
print(symbols)  # 输出: ['BTCUSDT', 'EOSUSDT']

2. 普通循环(易读性优先写法)

如果需要更清晰的执行步骤,用普通循环实现:

symbols = []
for item in data:
    # 先检查'symbol'键是否存在,防止出现KeyError
    if 'symbol' in item:
        symbols.append(item['symbol'])
print(symbols)

3. 筛选特定symbol值

如果只需要提取BTCUSDT和EOSUSDT这两个目标值,可以加入筛选条件:

targets = {'BTCUSDT', 'EOSUSDT'}
filtered_symbols = [item['symbol'] for item in data if 'symbol' in item and item['symbol'] in targets]
print(filtered_symbols)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 05:03:36