简体   繁体   English

如何遍历 dict 结构中的列表?

[英]How can I iterate over a list within a dict structure?

I make an API call which returns a json response stocks like so ( entire response I am trying to loop):我做了一个 API 调用,它返回一个 json 响应stocks ,就像这样(整个响应我试图循环):

{
    "data": [{
        "symbol": "000",
        "name": "Greenvolt - Energias Renováveis, S.A.",
        "currency": "EUR",
        "exchange": "FSX",
        "country": "Germany",
        "type": "Common Stock"
    }, {
        "symbol": "000",
        "name": "Greenvolt - Energias Renováveis, S.A.",
        "currency": "EUR",
        "exchange": "Munich",
        "country": "Germany",
        "type": "Common Stock"
    }, {

Now I want to iterate over the items within data but I'm confused about the returned structure (looks like a dict in a list in a dict somewhat?)现在我想遍历data中的项目,但我对返回的结构感到困惑(看起来有点像字典中的列表中的字典?)

What I've tried:我试过的:

stocks = td.get_stocks_list().as_json()[0]

print(type(stocks)) # prints 'dict'

print(stocks) # however this only prints the second item, not the first nor the entire dict I want to loop:

{'symbol': '000', 'name': 'Greenvolt - Energias Renováveis, S.A.', 'currency': 'EUR', 'exchange': 'Munich', 'country': 'Germany', 'type': 'Common Stock'}

So how to catch all items within data in the response?那么如何在响应中捕获data中的所有项目呢?

Your print command is outside of the loop so it should be您的打印命令在循环之外,所以它应该是

stocks_new = {}

for stock in stocks:
    stocks_new = stock
    print(stocks_new)

Below is the solution for the API call, using the requests module in python, in your last case if you write the print inside the loop then it will work,下面是 API 调用的解决方案,使用 python 中的requests模块,在最后一种情况下,如果您在循环中编写打印,那么它将起作用,

import requests
response = requests.get("https://api.twelvedata.com/stocks?source=docs")
for _res in response.json()["data"]:
       print(_res)
       print(_res["country"])
   

I have also show an example on how can you access the keys like country inside the array of dict.我还展示了一个示例,说明如何访问字典数组中的国家/地区等键。

Yeah since the whole object is dict where in your snapshot has the key data which is list of nasty dicts you would need to do something like this:是的,因为整个 object 是 dict ,在您的快照中有关键data是讨厌的 dicts 列表,您需要执行以下操作:

dict = {
    “data”: [{
        “symbol”: “000”,
        “name”: “Greenvolt - Energias Renováveis, S.A.“,
        “currency”: “EUR”,
        “exchange”: “FSX”,
        “country”: “Germany”,
        “type”: “Common Stock”
    }, {
        “symbol”: “000",
        “name”: “Greenvolt - Energias Renováveis, S.A.“,
        “currency”: “EUR”,
        “exchange”: “Munich”,
        “country”: “Germany”,
        “type”: “Common Stock”
    }]
}
print(dict.keys())
print(list(dict.keys()))
for key in list(dict.keys()):
    print(key, ‘->‘, list(dict[key]) )
    for nasty_dict in list(dict[key]):
        print(nasty_dict, ‘->‘, list(dict[key]).index(nasty_dict))
        for k in nasty_dict:
            print(k, ‘->’, nasty_dict[k])

which would output you this:这将 output 你这个:

dict_keys(['data'])
['data']
data -> [{'symbol': '000', 'name': 'Greenvolt - Energias Renováveis, S.A.', 'currency': 'EUR', 'exchange': 'FSX', 'country': 'Germany', 'type': 'Common Stock'}, {'symbol': '000', 'name': 'Greenvolt - Energias Renováveis, S.A.', 'currency': 'EUR', 'exchange': 'Munich', 'country': 'Germany', 'type': 'Common Stock'}]
{'symbol': '000', 'name': 'Greenvolt - Energias Renováveis, S.A.', 'currency': 'EUR', 'exchange': 'FSX', 'country': 'Germany', 'type': 'Common Stock'} -> 0
symbol -> 000
name -> Greenvolt - Energias Renováveis, S.A.
currency -> EUR
exchange -> FSX
country -> Germany
type -> Common Stock
{'symbol': '000', 'name': 'Greenvolt - Energias Renováveis, S.A.', 'currency': 'EUR', 'exchange': 'Munich', 'country': 'Germany', 'type': 'Common Stock'} -> 1
symbol -> 000
name -> Greenvolt - Energias Renováveis, S.A.
currency -> EUR
exchange -> Munich
country -> Germany
type -> Common Stock

and that how you could iterate over all objects以及如何遍历所有对象

As you had written your code before the edit of your question, the print statement was placed outside of the loop and only the last element of stocks would be printed.正如您在编辑问题之前编写的代码一样, print语句被放置在循环之外,并且只会打印stocks的最后一个元素。

This should print all elements of stocks :这应该打印stocks的所有元素:

for stock in stocks:
    print(stock)

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

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