当Json键被另一个替换时发生循环错误

时间:2019-03-16 12:12:47

标签: python json

我创建了一个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'

谢谢

2 个答案:

答案 0 :(得分:1)

您需要检查字典中是否存在键,您正在根据该键查找值

您不应覆盖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)

答案 1 :(得分:0)

if ad['price'][0] not in ads:

已经查找了ad['price'],因此如果字典中根本没有price,则ad['price']将无效,因此会导致键错误。

检查

if 'price' not in ads:

相反。