+3 votes
in Programming Languages by (56.5k points)
I want to initialize a dictionary such that all keys have an empty list as values. How can I do this?

e.g.

{1: [], 2: [], 3: [], 4: [], 5: []}

1 Answer

+2 votes
by (73.8k points)
selected by
 
Best answer

You can use zip() and dict() functions together to create a dictionary such that all keys have an empty list as values.

In the following example, I have declared two lists: a anb b. a has keys and b has values of the dictionary.

>>> a=[1,2,3,4,5]
>>> b=[[] for _ in range(len(a))]
>>> b
[[], [], [], [], []]
>>> aa=dict(zip(a,b))
>>> aa
{1: [], 2: [], 3: [], 4: [], 5: []}
>>>
 


...