Home > database >  Python try & expect for multiple appends in for loop
Python try & expect for multiple appends in for loop

Time:09-29

data = {"Street" : [],
        "City" : [],
        "State" : [],
        "ZIP" : [],
        "Status" : []}

counter = 0

for i in rows:

    if len(i) == 4:

        data["Street"].append(i[2][2:])

        data["City"].append(i[3][2:-2])

        data["State"].append(i[3][-2])

        data["ZIP"].append(i[3][-1])

        data["Status"].append(i[0][-1])

I'm looping over a nested lists rows, there are cases where the items were not in the lists, in that case, I get the below error

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-6-6b86cd54b28b> in <module>()
     29     data["Street"].append(i[2][2:])
     30 
---> 31     data["City"].append(i[3][2:-2])
     32 
     33     data["State"].append(i[3][-2])

IndexError: list index out of range

To eliminate this error, I want to append items only if it exists, if it doesn't exist I want to add None

for i in rows:

    if len(i) == 4:

        try:
            data["Street"].append(i[2][2:])
        
        except Exception as E:
            data["Street"].append(None)

        try:

            data["City"].append(i[3][2:-2])

        except Exception as E:
            data["City"].append(None)

        try:
            data["State"].append(i[3][-2])
        except Exception as E:
            data["State"].append(None)

        try: 
            data["ZIP"].append(i[3][-1])

        except Exception as E:
            data["ZIP"].append(None)

        try:
            data["Status"].append(i[0][-1])

        except Exception as E:
            data["Status"].append(None)


        # Ans soooo on

Instead of adding multiple try & except for each append Is there a better way of doing this...

CodePudding user response:

I don't really know what you want to do. I suspect you're trying to parse an address (and yes, there are likely much better ways to do it), but given your current code, you could simplify it using a dictionary of the slices to extract:

slices = {'Street': (2, slice(2, None)),  # 2  ;  2:
          'City':   (3, slice(2, -2)),    # 3  ;  2:-2
          'State':  (3, -2),              # 3  ; -2
          # ...
         }

for i in rows:
    if len(i) == 4:
        for k, (a,b) in slices.items():
            try:
                data[k].append(i[a][b])
            except:
                data[k].append(None)

NB. in except a good practice would be to specify which kind of Exception you expect (e.g., except IndexError:)

CodePudding user response:

You can adapt this approach:-

data = {"Street": [],
        "City": [],
        "State": [],
        "ZIP": [],
        "Status": []}


def da(a, r, i, s):
    try:
        a.append(r[i][s])
    except IndexError:
        a.append(None)


da(data['Street'], [], 2, slice(2, None))
da(data['City'], [], 3, slice(2, -2))
da(data['State'], [], 3, -2)
da(data['ZIP'], [], 3, -1)
da(data['Status'], [], 0, -1)

print(data)
  • Related