kir.pir
kir.pir

Reputation: 77

How to set a default value for key in dict, when the key value is not found in the dict in python

I am trying to scrape some results from ebay with python and I am running into an error :

condition = item['condition'][0]['conditionDisplayName'][0]
>>> KeyError: 'condition'`

This is the code in question :

for item in (parseddoc["findItemsByKeywordsResponse"][0] ["searchResult"][0]["item"]):
    condition = item['condition'][0]['conditionDisplayName'][0]
    print(condition)

I am trying to figure out a way to stop it from getting the error and just default to a preset value( "N/A" for example ) and continue with the loop. What's the best way to achieve that? Thanks

Upvotes: 1

Views: 594

Answers (2)

jpp
jpp

Reputation: 164623

Use a try / except clause to catch KeyError:

for item in parseddoc["findItemsByKeywordsResponse"][0]["searchResult"][0]["item"]:

    try:
        condition = item['condition'][0]['conditionDisplayName'][0]
    except KeyError:
        condition = 'N/A'

    print(condition)

Upvotes: 3

BioGeek
BioGeek

Reputation: 22827

Add the following if/else statement to your loop:

for item in (parseddoc["findItemsByKeywordsResponse"][0]["searchResult"][0]["item"]):
    if 'condition' not in item:
        condition = 'N/A'
    else:
        condition = item['condition'][0]['conditionDisplayName'][0]
    print(condition)

Upvotes: 0

Related Questions