Search code examples
jsonpython-3.xlistdictionarytry-except

try-except and a list of dictionary


I have a list of dictionaries to describe the format. I would like to print only "US" using try/except construct. Because I might have more lists, which don't have a "nationality" tag. I only think of if/else construct. Please help me. Thanks!

list_components = js['results'][0]['list_components']
    try:
        for item in list_components:
            item["types"] == ["nationality", "political"]
            print('The nationality information for the list:', item["short_name"])
                          
    except:
        print('No nationality is available for this list.')

Solution

  • Here is a very naive approach to what you want to achieve. But this is not considered a good practice. It's like making something out of something and ignoring all the good rules programmers adopt.

    list_components = js['results'][0]['list_components'] 
    
    for item in list_components:
        try:
            #Generate error when there is no nationality otherwise print nationality 
            status = item["types"][0] == "nationality"
            status and print("Nationality: ", item["short_name"])
            raise ValueError
        except:
            #Print prompt
            not status and print("No Nationality")
    

    This solution does not require any try/catch construct and can be solved purely with if-else. In case anyone else needs it, here is a better and simple solution.

    for item in list_components:
        print("Nationality: " item["short_name"]) if item["types"][0] == "nationality" else print("No Nationality")