Search code examples
pythonjsonpython-3.xrdap

More elegant way to deal with multiple KeyError Exceptions


I have the following function, which reads a dict and affects some values to local variables, which are then returned as a tuple.

The problem is that some of the desired keys may not exist in the dictionary.

So far I have this code, it does what I want but I wonder if there is a more elegant way to do it.

def getNetwork(self, search):

    data = self.get('ip',search)
    handle         = data['handle']
    name           = data['name']
    try:
        country        = data['country']     
    except KeyError:
        country = ''
    try:       
        type           = data['type']
    except KeyError:
        type = ''
    try:                
        start_addr     = data['startAddress']
    except KeyError:
        start_addr = ''
    try:                 
        end_addr       = data['endAddress']
    except KeyError:
        end_addr = '' 
    try:                  
        parent_handle  = data['parentHandle']
    except KeyError:
        parent_handle = ''   
    return (handle, name, country, type, start_addr, end_addr, parent_handle)

I'm kind of afraid by the numerous try: except: but if I put all the affectations inside a single try: except: it would stop to affect values once the first missing dict key raises an error.


Solution

  • Just use dict.get. Each use of:

    try:
        country        = data['country']     
    except KeyError:
        country = ''
    

    can be equivalently replaced with:

    country = data.get('country', '')