API列表仅返回最后一项,而不是所有列表

时间:2020-08-13 21:12:07

标签: python string list api

endpoint = 'http://api.yelp.com/v3/categories' #url categories 
headers = {'Authorization': 'bearer %s'% api_key} #making it bearer, not changing it throughout 

response3 = requests.get(url = endpoint, headers = headers)
business_data2 = response3.json()

for item in business_data2['categories']:
     itemname = item['title']

如果我说

itemname = item['title']

我只得到API中的最后一句话

但是如果我说

print(item['title'])

我得到了所有列表,但仅在我的for循环中。 我试图在终端上做到这一点 我只有最后一个字符串

我不知道如何解决它 我尝试通过说[0:-1]来为其编制索引,但我也只得到最后一个元素。

1 个答案:

答案 0 :(得分:1)

通过执行以下操作,您将继续覆盖itemname值,因此您只能看到最后一个值

for item in business_data2['categories']:
    itemname = item['title']

要收集它们,请使用list

itemnames = [] 
for item in business_data2['categories']:
    itemnames.append(item['title'])


# or directly a list comprehension
itemnames = [item['title'] for item in business_data2['categories']]

# pythonic equivalent
from operator import itemgetter
itemnames = list(map(itemgetter('title'), business_data2['categories']))