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