8

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?

6
  • 1
    setdefault sets default value for a concrete key, not for a type of key. A defaultdict might serve your purposes: from collections import defaultdict d = defaultdict(lambda: []) Feb 14, 2016 at 11:19
  • First, you should not redefine reserved names like dict, as you will not be able to use original object further. Second, dict.[0].append(1) is syntactically invalid
    – Oleksii M
    Feb 14, 2016 at 11:19
  • 1
    Please edit your question to show the actual code you used, and the traceback. Feb 14, 2016 at 11:21
  • 2
    @schwobaseggl: Or just d = defaultdict(list): no need for the lambda. Feb 14, 2016 at 11:22
  • @MarkDickinson aw, that's even more intuitive. Thx! Feb 14, 2016 at 11:25

2 Answers 2

8

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

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

df.reset_index(inplace = True)

1
  • This question has nothing to do with pandas. It hasn't anything named df. Did you answer by accident to another question than the one you intended to answer?
    – chrslg
    Nov 6, 2022 at 14:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.