子列表值为两个不同的变量?

问题描述 投票:0回答:1

我正在尝试将列表的两个值分配给两个不同的变量。这是json列表。它提高了key error。请让我知道我错在哪里。

[{'min': 1.158, 'max': 1.150, 'id': 269097, 'to': 1532003820, 'from': 1532003760, 'check': 1.15852, 'no_check': 1.15822, 'volume': 0},{'min': 1.1, 'max': 1.17, 'id': 269098, 'to': 1532003880, 'from': 1532003820, 'check': 1.158615, 'nocheck': 1.158515, 'volume': 0}]

这是我的代码python3代码:

pt = [{'min': 1.158, 'max': 1.150, 'id': 269097, 'to': 1532003820, 'from': 1532003760, 'check': 1.15852, 'no_check': 1.15822, 'volume': 0},{'min': 1.1, 'max': 1.17, 'id': 269098, 'to': 1532003880, 'from': 1532003820, 'check': 1.158615, 'nocheck': 1.158515, 'volume': 0}]

y = [item[0] for item in pt]
z = [item[0] for item in pt]
print(y)
print(z)

错误:

File "test_YourM.py", line 19, in <module>
  y = [item[0][0] for item in pt]   File "test_YourM.py", line 19, in <listcomp>
  y = [item[0][0] for item in pt] KeyError: 0

预期产量:

print(y) # {'min': 1.158, 'max': 1.150, 'id': 269097, 'to': 1532003820, 'from': 1532003760, 'check': 1.15852, 'no_check': 1.15822, 'volume': 0}
print(z) # {'min': 1.1, 'max': 1.17, 'id': 269098, 'to': 1532003880, 'from': 1532003820, 'check': 1.158615, 'nocheck': 1.158515, 'volume': 0}
python python-3.x python-requests subprocess
1个回答
0
投票
[item for item in pt[0]]
[item for item in pt[1]]

该项是在该范围内生成的,而pt不是,即使你枚举一个字典,你可能想要这样做:

{key: value for key, value  in pt[0].items()}
{key: value for key, value  in pt[1].items()}
© www.soinside.com 2019 - 2024. All rights reserved.