pythonkey

How to skip key error in pandas?


I have a dictionary and a list. For each key in the list, I want to plot the associated values with that key.

I have the following code in pandas:

import numpy as np; np.random.seed(22)
import seaborn as sns; sns.set(color_codes=True)

window = int(math.ceil(5000.0 / 100))
xticks = range(-2500,2500,window)

sns.tsplot([mydictionary[k] for k in mylist],time=xticks,color="g")

plt.legend(['blue'])

However, I get KeyError: xxxx

I can manually remove all problematic keys in my list, but that will take a long time. Is there a way I can skip this key error?


Solution

  • If you are looking for a way to just swallow the key error, use a try & except. However, cleaning up the data in advance would be much more elegant.

    Example:

    mydictionary = {
        'a': 1,
        'b': 2,
        'c': 3,
    }
    
    mylist = ['a', 'b', 'c', 'd']
    
    result = []
    for k in mylist:
        try:
            result.append(mydictionary[k])
        except KeyError:
            pass
    
    print(result)
    
    >>> [1, 2, 3]
    

    You will need to construct the list prior to using it in your seaborn plot. Afterwards, pass the list with the call: sns.tsplot(result ,time=xticks,color="g")