I'm looping through a list of dictionaries and creating a dataframe, but I'm running into an issue if keys are missing. I can use "try: except:" for exception handling, but there are a lot of keys and I would prefer to use a custom function to reduce the amount of code.

I can't simply do this to to create my dataframe, by the way, due to the complexity of the list of dictionaries in my actual scenario:

```
# can't do this    
df = pd.DataFrame(dict_list)

```

Example data and error if keys are missing:

```
dict_list =[{'city':'smithville','zip':1234},{'city':'toonville'}]

df = pd.DataFrame()
for ind,val in enumerate(dict_list):
    city = dict_list[ind]['city']
    zip = dict_list[ind]['zip']
    df1 = pd.DataFrame({'city':[city], 'zip_code':[zip]})
    df = pd.concat([df,df1])

```

Error:

```
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-52-0c2951af44ad> in <module>
      2 for ind,val in enumerate(dict_list):
      3     city = dict_list[ind]['city']
----> 4     zip = dict_list[ind]['zip']
      5     df1 = pd.DataFrame({'city':[city], 'zip_code':[zip]})
      6     df = pd.concat([df,df1])

KeyError: 'zip'

```

This works:

```
df = pd.DataFrame()
for ind,val in enumerate(dict_list):
    city = dict_list[ind]['city']
    try:
        zip = dict_list[ind]['zip']
    except:
        zip = np.nan
    df1 = pd.DataFrame({'city':[city], 'zip_code':[zip]})
    df = pd.concat([df,df1])

df

    city    zip_code
0   smithville  1234.0
0   toonville   NaN

```

I'd like to use a function to accomplish the above exception handling but I'm struggling with this piece. This is what I have so far but it doesn't work:

```
def get_value(x,y):
    try:
        x = y
        return(x)
    except KeyError:
        x = np.nan

df = pd.DataFrame()
for ind,val in enumerate(dict_list):
    get_value(city,dict_list[ind]['city'])
    df1 = pd.DataFrame({'city':[city]})
    df = pd.concat([df,df1])

```

Error

```
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-67-3a634901ade7> in <module>
      1 df = pd.DataFrame()
      2 for ind,val in enumerate(dict_list):
----> 3     get_value(city,dict_list[ind]['city'])
      4     df1 = pd.DataFrame({'city':[city]})
      5     df = pd.concat([df,df1])

NameError: name 'city' is not defined

```