Skip to main content
 首页 » 编程设计

python之当 Json 键被另一个键替换时出现 for 循环错误

2024年11月24日12飞鱼

我创建了一个 for 循环来查找 Json 文件中的键,当 price 键被“price_calendar”键替换时,我遇到了一个问题。
当客户没有在他的广告中标价时出现。
我试图用 if 语句来解决这个错误,但它不起作用。
如果有人能解释为什么它不起作用。

response = requests.post(url, headers=headers,  
data=json.dumps(payload)) 
status = response.status_code 
result = response.json() 
ads = result['ads'] 
 
for ad in ads:  
  id = ad['list_id'] 
  print(id) 
  title = ad['subject'] 
  print(title) 
  url = ad['url'] 
  print(url) 
  if ad['price'][0] not in ads: 
    print ('No price') 
  else: 
    price = ad['price'][0] 
    print (price,"$") 
  date = ad['first_publication_date'] 
  print(date) 

错误:

Exception has occurred: KeyError 'price' 

谢谢

请您参考如下方法:

您需要检查字典中是否存在您正在查找的基于该键的值

你不应该覆盖 id() 函数中的构建

for ad in ads:  
  id = ad['list_id'] 
  print(id) 
  title = ad['subject'] 
  print(title) 
  url = ad['url'] 
  print(url) 
 
  #if 'price' not in ad.keys() or ad['price'][0] not in ads: 
  #    print ('No price') 

由于问题所有者只想检查价格是否在字典键中的任务上下文而更改

  if 'price' not in ad.keys(): 
    print ('No price') 
 
  else: 
    price = ad['price'][0] 
    print (price,"$") 
  date = ad['first_publication_date'] 
  print(date)