python-How to solve KeyError: 2?

Question:

I have a dict which is formatted as {int:[]}

When I was trying to set value to a key-value pair where the value list is NULL, I got KeyError: 2

tags = {}
tags.setdefault(int,[])
for tag_id in (db.session.query(PostTagRel).filter(PostTagRel.id == post_id).first().tag_id.split(',')):
            tag = db.session.query(Tag).filter(Tag.tag_id == tag_id).first().tag_name
            tags[post_id].append(tag)

What should I do?

Asked By: jinglei

||

Answers:

In order to set a general default value for all keys, you can use defaultdict:

from collections import defaultdict

d = defaultdict(list)    
d[0].append(1)
Answered By: user2390182

It might be because of index formatting not properly done: just try

df.reset_index(inplace = True)

Answered By: user20394963
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.