+3 votes
in Programming Languages by (17.9k 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

+1 vote
by (28.5k points)

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


...