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?
setdefault
sets default value for a concrete key, not for a type of key. Adefaultdict
might serve your purposes:from collections import defaultdict
d = defaultdict(lambda: [])
dict
, as you will not be able to use original object further. Second,dict.[0].append(1)
is syntactically invalidd = defaultdict(list)
: no need for thelambda
.