>>> keys = [1, 2, 3]
>>> d = dict(zip(keys, [[]]*len(keys)))
>>> d
{1: [], 2: [], 3: []}
>>> d[1].append(100)
>>> d
{1: [100], 2: [100], 3: [100]}
即使复制[]也无效:
{1:[100],2:[],3:[]} 是我想要的。
答案 0 :(得分:1)
keys = [1, 2, 3]
d = dict(zip(keys, [[] for _ in keys]))
d[1].append(100)
根据abarnert的评论,您可以使用dictionary comprehension使代码更简单:
keys = [1, 2, 3]
d = {key:[] for key in keys}
d[1].append(100)
同时使用两个选项调用d
会得到以下输出:
{1: [100], 2: [], 3: []}