【问题标题】:How can I solve IndexError: list index out of range in a list of dict?如何解决 IndexError: list index out of range in a list of dict?
【发布时间】:2021-02-28 18:09:37
【问题描述】:

我得到以下代码

Traceback(最近一次调用最后一次):文件“main.py”,第 24 行,在 artist_uri = json_data['artists']['items'][0]['id'] IndexError: list index out of range.

谁能告诉我如何解决这个问题?

for item in (fd):
  
  artist = item['Name']
  headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Authorization': 'Bearer xxxxx',
    }

  params = (
    ('q', artist),
    ('type', 'artist'),
    )
  response = requests.get('https://api.spotify.com/v1/search', headers=headers, params=params)
  
  json_data = json.loads(response.text) # convert json response to text/dict
  artist_uri = json_data['artists']['items'][0]['id']
  print(artist_uri)

【问题讨论】:

    标签: python api index-error


    【解决方案1】:

    这是因为无法从 Spotify API 检索艺术家:“ANAVITÃÂRIA”。以下是您的脚本在尝试时得到的响应:

    {
      "artists" : {
        "href" : "https://api.spotify.com/v1/search?query=ANAVIT%C3%83%C2%83%C3%82%C2%93RIA&type=artist&offset=0&limit=20",
        "items" : [ ],
        "limit" : 20,
        "next" : null,
        "offset" : 0,
        "previous" : null,
        "total" : 0
      }
    

    有时可能是由于名称中的字符。为了避免这个错误,限速问题并继续循环,您可以检查当前API响应中是否有数据以及API响应的状态码检查更新的代码:(请在尝试时更新承载令牌)

    import pandas as pd
    import requests
    import json
    import time
    
    fd = pd.read_csv('fd.csv',sep=';',encoding='latin1') # Reading data from csv
    fd = fd.T.to_dict().values() # Converting dataframe into list of dictionaries
    
    for item in (fd):
      
      artist = item['Name']
      headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer xxxxxx',
        }
    
      params = (
        ('q', artist),
        ('type', 'artist'),
        )
      
    
      response = requests.get('https://api.spotify.com/v1/search', headers=headers, params=params)
      if response.status_code != 429:
        json_data = json.loads(response.text) # convert json response to text/dict
        
        if (len(json_data['artists']['items']) > 0):
          artist_uri = json_data['artists']['items'][0]['id']
          print(artist_uri)
      else:
        time.sleep(30)
        response = requests.get('https://api.spotify.com/v1/search', headers=headers, params=params)
        json_data = json.loads(response.text) # convert json response to text/dict
        
        if (len(json_data['artists']['items']) > 0):
          artist_uri = json_data['artists']['items'][0]['id']
          print(artist_uri)
    

    【讨论】:

    • 非常感谢您的回答。但是,我是初学者,这个版本对我来说真的很复杂。 encoding='latin1' 不应该解决非拉丁字符的问题?
    • 我只修改了你的几行代码就可以了。我认为“latin-1”中的编码不会解决问题,因为艺术家的名字以不同的方式传递给 API。如果有帮助,请投票或批准此答案:)
    猜你喜欢
    • 2022-10-09
    • 1970-01-01
    • 2019-02-23
    • 1970-01-01
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 2018-02-08
    相关资源
    最近更新 更多