How to get keys and values from a dictionary within a list within a dictionary
我想从字典中的列表中获取值。当我发出OANDA REST-API请求时,会得到以下JSON数据结构。
当我使用get函数时,我可以从"trades"和"lasttransactionid"访问dict和keys及其值,但不知道如何获取"trades"键中的列表项。
如果你能帮我把这事办好,我会非常感激的
作品打印RV.GET("交易")。
不工作打印rv.get("交易").get("融资")。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | { "trades": [ { "financing":"0.0000", "openTime":"2017-11-08T17:21:49.533679739Z", "price":"1.15901", "unrealizedPL":"-0.0001", "realizedPL":"0.0000", "instrument":"EUR_USD", "state":"OPEN", "initialUnits":"1", "currentUnits":"1", "id":"2046" }, { "financing":"0.0000", "openTime":"2017-11-08T17:19:27.343697147Z", "price":"1.15905", "unrealizedPL":"-0.0001", "realizedPL":"0.0000", "instrument":"EUR_USD", "state":"OPEN", "initialUnits":"1", "currentUnits":"1", "id":"2044" } ], "lastTransactionID":"2046" } |
谢谢你的帮助和亲切的问候
只需遍历列表:
1 2 | for trade in rv.get("trades"): print trade.get("financing") |
另一个不错的选择是使用列表理解,这将允许一行解决方案:
1 | [trade.get("financing") for trade in rv.get("trades")] |
请注意,这并不比@bahrom的回答好,我认为这更像是Python。
1 2 | rv.get("trades")[0].get("financing") rv.get("trades")[1].get("financing") |
所以您需要迭代列表
1 2 | for item in rv.get('trades'): print(item.get('financing')) |
您只需要遍历列表:
这里演示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | data = { "trades": [ { "financing":"0.0000", "openTime":"2017-11-08T17:21:49.533679739Z", "price":"1.15901", "unrealizedPL":"-0.0001", "realizedPL":"0.0000", "instrument":"EUR_USD", "state":"OPEN", "initialUnits":"1", "currentUnits":"1", "id":"2046" }, { "financing":"0.0000", "openTime":"2017-11-08T17:19:27.343697147Z", "price":"1.15905", "unrealizedPL":"-0.0001", "realizedPL":"0.0000", "instrument":"EUR_USD", "state":"OPEN", "initialUnits":"1", "currentUnits":"1", "id":"2044" } ], "lastTransactionID":"2046" }; for d in data['trades']: print(d['openTime']) |
这种回报:
1 2 | 2017-11-08T17:21:49.533679739Z 2017-11-08T17:19:27.343697147Z |