Alex
Alex

Reputation: 59

How do I add keys dynamically to a dictionary?

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

Upvotes: 2

Views: 8007

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 600059

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}

Upvotes: 6

Related Questions