Python: My dictionary that stores first names won't store more than one first name at a time
So, I've created a Dictionary that stores first-names as a list within that dictionary. New names are added within the dictionary's list via a function. Now, this is where i have hit a snag:
Mai开发者_Go百科n Obstacle: The function overwrites new names that I add. If I add the name "George" to the list via the function, it will store the name "George". But, I want to add the name "Alfred" within the dictionary, it overwrites the name "George" and adds the name "Alfred".
I am sure you can see how problematic this is for someone who wants to add multiple names to the dictionary's list. The odd thing is that when I type out the exact same code into the interpreter and I individually append names to the dictionary's list, it works fine.
Here is the code:
def add(data,value):
data['names'] = {}
data['names']['first'] = []
data['names']['first'].append(value)
Didn't you ask this question already? (My previous answer)
You are always setting the data['names']
to an empty dictionary before appending value to it.
def add(data, value):
data.setdefault('names', {}).setdefault('first', []).append(value)
See python docs on dict.setdefault
精彩评论