原始代码:
from typing import Dictrelated_objects_for_fetch: Dict[str, list] = {}for key, value in [('k1', 'v1'), ('k1', 'v2'), ('k2', 'v2'), ('k3', 'v3'), ('k2', 'v2')]:if key not in related_objects_for_fetch:related_objects_for_fetch[key] = []if value not in (values := related_objects_for_fetch[key]):values.append(value)for k, v in related_objects_for_fetch.items():print(k, v)
修改后:
from collections import defaultdictrelated_objects_for_fetch: defaultdict[str, list] = defaultdict(list)for key, value in [('k1', 'v1'), ('k1', 'v2'), ('k2', 'v2'), ('k3', 'v3'), ('k2', 'v2')]:if value not in (values := related_objects_for_fetch[key]):values.append(value)for k, v in related_objects_for_fetch.items():print(k, v)
少了if key not in xxx的判断,代码更加简洁。
需要注意的是:
my_dict['not-exist-key']这个会抛出KeyError
而my_defaultdict['not-exist-key']则会返回空列表
如下图: