简体   繁体   English

如何从 Python 中的复杂列表中提取元素

[英]How to extract elements from a complex list in Python

I have a list like this:我有一个这样的列表:

ls = {
    'info': {
        'id': '237371250',
        'market': 'BCH-PERP',
        'future': 'BCH-PERP',
        'side': 'sell',
        'type': 'stop',
        'orderPrice': None,
        'triggerPrice': '104.2',
        'size': '83.33',
        'status': 'open',
        'createdAt': '2022-07-16T12:25:02.288247+00:00',
        'triggeredAt': None,
        'orderId': None,
        'error': None,
        'reduceOnly': True,
        'trailValue': None,
        'trailStart': None,
        'cancelledAt': None,
        'cancelReason': None,
        'retryUntilFilled': True,
        'orderType': 'market',
        'filledSize': '0.0',
        'avgFillPrice': None},
    'id': '237371250',
    'clientOrderId': None,
    'timestamp': 1657974302288,
    'datetime': '2022-07-16T12:25:02.288Z',
    'lastTradeTimestamp': None,
    'symbol': 'BCH/USD:USD',
    'type': 'stop',
    'timeInForce': None,
    'postOnly': None,
    'reduceOnly': True,
    'side': 'sell',
    'price': 104.2,
    'stopPrice': 104.2,
    'amount': 83.33,
    'cost': 0.0,
    'average': None,
    'filled': 0.0,
    'remaining': 83.33,
    'status': 'open',
    'fee': None,
    'trades': [],
    'fees': []}

I would like to extract the 'triggerPrice' value of 104.2 from it.我想从中提取104.2'triggerPrice'值。 How would I go about doing that?我该怎么做呢?

I have tried ls['triggerPrice'] but that returns an error.我试过ls['triggerPrice']但这会返回错误。

Any information about what kind of data structure this is and how to access its elements would be gratefully received.任何有关这是哪种数据结构以及如何访问其元素的信息都将不胜感激。

This datastructure is called a dictionary ( dict ) and it works the same way as JSON, just the types are Pythonic.这种数据结构称为字典dict ),它的工作方式与 JSON 相同,只是类型是 Pythonic。

Eg: A typical JSON file would be like this例如:一个典型的 JSON 文件是这样的

{
    "id": 2,
    "name": null,
    "is_allowed": false
}

in python it would be something like this在python中它会是这样的

{
    "id": 2,
    "name": None,
    "is_allowed": False,
}

As you can see, only the types are changed.如您所见,仅更改了类型。

To access elements in a dictionary, you just put the name of the dict, eg ls , then lookup a value in the dict with a key: ls["id"]要访问字典中的元素,只需输入字典的名称,例如ls ,然后使用键在字典中查找值: ls["id"]

The solution to your question will be ls["info"]["triggerPrice"]您的问题的解决方案是ls["info"]["triggerPrice"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM