python-如何解决KeyError:2?

jin*_*lei 6 python dictionary keyerror

我有一个格式为的字典 {int:[]}

当我尝试将值设置为值列表为 NULL 的键值对时,我得到了 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)
Run Code Online (Sandbox Code Playgroud)

我该怎么办?

sch*_*ggl 5

为了为所有键设置通用默认值,您可以使用defaultdict

from collections import defaultdict

d = defaultdict(list)    
d[0].append(1)
Run Code Online (Sandbox Code Playgroud)