如何建立一个所有值都是Python中[]的独立实例的dict?

时间:2018-08-29 01:16:17

标签: python list dictionary copy deep-copy

>>> 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]}

即使复制[]也无效:

  • dict(zip(keys,[[] [:]] * len(keys)))
  • dict(zip(键,[copy.deepcopy([]]] * len(键)))

{1:[100],2:[],3:[]} 是我想要的。

1 个答案:

答案 0 :(得分:1)

尝试list comprehension

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: []}