简体   繁体   English

如何解决 IndexError: list index out of range in a list of dict?

[英]How can I solve IndexError: list index out of range in a list of dict?

for the following code I am getting对于以下代码,我得到

Traceback (most recent call last): File "main.py", line 24, in artist_uri = json_data['artists']['items'][0]['id'] IndexError: list index out of range.回溯(最近一次调用):文件“main.py”,第 24 行,在artist_uri = json_data['artists']['items'][0]['id'] 索引错误:列表索引超出范围。

Anyone can tell me how to solve this?谁能告诉我如何解决这个问题?

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)

This is because the artist: "ANAVITÃÂRIA" cannot be retrieved from the Spotify API.这是因为无法从 Spotify API 中检索到艺术家:“ANAVITÃÂRIA”。 The following is the response your script get when you try it:以下是您的脚本在尝试时得到的响应:

{
  "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
  }

Sometimes it is might be due to the characters in the name.有时可能是由于名称中的字符。 To avoid this error, rate-limiting issue and continue the loop you can check whether there are data in the current API response and also the status code of the API Response Check the updated code: (Please update the bearer token when you try it)为了避免这个错误,限速问题并继续循环您可以检查当前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)

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

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