python dict 相同key 合并value

# #### dict中将key相同的字典合并在一个对象里
"""
a = {"a": 1, "b": 2, "c": 1}
for k, v in a.iteritems():
    tmp.setdefault(v, []).append(k)
"""
tmp = {}
objs = OnlineScoringTeacher.objects.filter(
    entry__message_ila__id=1038,
    teacher=1,
).select_related('entry')
# 常规方法
for obj in objs:
    if obj.entry.subject_id not in tmp:
        tmp.update({
            obj.entry.subject_id: []
        })
    tmp[obj.entry.subject_id].append(obj)
# 法二
for obj in objs:
    tmp.setdefault(obj.entry.subject_id, []).append(obj)

你可能感兴趣的:(Python,Web,Python,Python,Scripts)