Python 3.x 从python中的元素列表中获取属性
我有这样一个例子:Python 3.x 从python中的元素列表中获取属性,python-3.x,Python 3.x,我有这样一个例子: listing = { "ret_code": 0, "ret_msg": "ok", "ext_code": "", "result": { "pages": 10, "data": [ <--- would like to get ALL information under "data" { "user_id": 1,
listing = {
"ret_code": 0,
"ret_msg": "ok",
"ext_code": "",
"result": {
"pages": 10,
"data": [ <--- would like to get ALL information under "data"
{
"user_id": 1,
"qty": 2,
"order_status": "Filled",
"ext_fields": {
"close_on_trigger": true,
"orig_order_type": "BLimit",
"o_req_num": -34799032763,
"xreq_type": "x_create"
},
"last_exec_price": 7070.5,
"leaves_qty": 0,
]
[... snip ...]
}
但我的结果如下:
data = [item for item in listing if item.attribute == 'data']
Traceback (most recent call last):
File "../trade_bybit/trade_bybit.py", line 198, in get_recent_orders
data = [item for item in listing if item.attribute == 'data']
File "../trade_bybit/trade_bybit.py", line 198, in <listcomp>
data = [item for item in listing if item.attribute == 'data']
AttributeError: 'dict' object has no attribute 'attribute'
但我得到的答案是:
[]
看起来“数据”
是字典中与键“结果”
对应的键因此,请使用:
[listing["results"][item] for item in listing["results"] if item == 'data']
或者只是:
[value for key,value in listing["results"].items() if key == 'data']
如果整个结构仅包含一个
“数据”
,则可以使用:
data = listing[0]['result']['data']
为什么要使用
item.attribute
当您可以执行[item for item in listing if item=='data']
感谢您的提示:)真正为我做的是:data=listing[0]['result']['data']-它正好得到了所需的数据。我剪下了一些片段(使文章变得更小),但我会放一个完整的例子来说明“正在进行的工作”
data = listing[0]['result']['data']