Alex Trevylan
Alex Trevylan

Reputation: 545

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?

Upvotes: 6

Views: 5120

Answers (2)

mvishnu
mvishnu

Reputation: 1190

Solved a similar problem with

[mydictionary[k] for k in mylist if k in mydictionary]

... that would skip over all k's in mylist that are not in the dictionary.

Upvotes: 0

Jan Trienes
Jan Trienes

Reputation: 2571

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")

Upvotes: 5

Related Questions