Neeko
Neeko

Reputation: 200

For loop error when Json key is replaced by an other one

I've made a for loop to find keys in a Json file, I've got an issue when the price key is replaced by 'price_calendar' key.
It appears when the customer doesn't put price in his ad.
I'm tring to go over this error with an if statement but it doesn't work.
If anyone can explain why it doesn't work.

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)

Error :

Exception has occurred: KeyError 'price'

Thanks

Upvotes: 2

Views: 64

Answers (2)

cheshire cat
cheshire cat

Reputation: 191

you need to check existence of key in dict you are looking value based on that key

you shouldn't override build in id() function

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')

changed due to task context where question owner wants only to check if price is in dict keys

  if 'price' not in ad.keys():
    print ('No price')

  else:
    price = ad['price'][0]
    print (price,"$")
  date = ad['first_publication_date']
  print(date)

Upvotes: 1

faho
faho

Reputation: 15934

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

already looks up ad['price'], so if there is no price at all in the dictionary, ad['price'] won't be valid and so it causes a key error.

Check

if 'price' not in ads:

Instead.

Upvotes: 0

Related Questions