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

时间:2018-07-19 12:55:03

标签: python python-3.x python-requests subprocess

我正在尝试将列表的两个值分配给两个不同的变量。这是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}

1 个答案:

答案 0 :(得分: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()}