如何将字典结果分配给python3中的各个变量?

时间:2018-07-08 08:35:13

标签: python python-3.6

我有这个结果:

{'orderId': 1234567, 'price': '20.5', 'qty': '125', 'status': 'open'}
{'orderId': 7654321, 'price': '15.5', 'qty': '15', 'status': 'open'}
{'orderId': 9876543, 'price': '32.0', 'qty': '102', 'status': 'open'}

我想将每个 orderID分配给单个变量,这样我就可以对它们进行处理。

以上结果通过过滤代码获得,如下所示:

orders = product.get_open_orders(product='sample')

keys = ['orderId', 'price', 'qty', 'status']
res = [{k: d[k] for k in keys} for d in orders]

for status in res:
    if status['status'] == 'open':
        print(status)

2 个答案:

答案 0 :(得分:0)

只需 BigDecimal d=new BigDecimal("3.1756").setScale(3,RoundingMode.DOWN);

<FormGroup controlId="gender">
  <ControlLabel>Gender</ControlLabel>
  <br />
  <Radio
    name="radioGroup"
    type="radio"
    inline
    value={this.state.gender === "male"}
  >
    onChange={this.handleChange}
    Male
  </Radio>
  <Radio
    name="radioGroup"
    type="radio"
    inline
    value={this.state.gender === "female"}
  >
    onChange={this.handleChange}
    Female
  </Radio>
</FormGroup>

这将创建status['orderId']count = 1 for status in res: if status['status'] == 'open': print(status) orderId = status['orderId'] eval("orderId"+str(count) + "=" + "orderId") ...

答案 1 :(得分:0)

如果需要一系列枚举项目,则正确的数据结构为list

orders = []
for status in res:
    if status['status'] == 'open':
        orders.append(status['orderId'])
print(orders)  # [1234567, 7654321, 9876543]
print(orders[0], orders[2])  # 1234567 9876543

或者,在更惯用的Python中:

orders = [status['orderId'] for status in res if status['status'] == 'open']
print(orders)  # [1234567, 7654321, 9876543]