How do I add keys dynamically to a dictionary?

Question:

 for x in names:
        dictionary = {x : [], }

I want my dictionary to have an empty list of every element of names, yet I’m only getting the last one (overriding, obviously). In lists we can use .append(). How do I do this with a dictionary?

Edit : Assuming names has Jimmy and Alex.

dictionary = {Jimmy : [], Alex : []}
Asked By: Alex

||

Answers:

Don’t create a new dict each time, instead add the name to the same one.

dictionary = {}
for x in names:
    dictionary[x] = []

or, for short:

dictionary = {x: [] for x in names}
Answered By: Daniel Roseman
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.