Python dictionaries-How to keep the new value from

2020-02-14 09:22发布

问题:

I want to create a Dictionary called "First" (as in First Name) that will store numerous first names which are all stored in the dictionary via a function. The idea is that the dictionary can support multiple names,

so here is my problem:

When I add a name to the dictionary, then I go to add a second one via the function, the previous name is overwritten by the last. How do I mend this? I know it involves something like a dictionary within a dictionary, or nested conditionals. Here is my code:

def store(data,value):
    data['Names'] = {}
    data['Names']['first'] = {}
    data['Names']['first'] = {value}

回答1:

Turn data['Names']['first'] in a list and append to it:

data['Names'] = {}
data['Names']['first'] = []

def store(data, value):
    data['Names']['first'].append(value)


回答2:

Python < 2.5 doesn't have defaultdict, however you can achieve the same thing in with ordinary dict too.

>>> names = {}
>>> name_list = [('Jon', 'Skeet'), ('Jeff', 'Atwood'), ('Joel', 'Spolsky')]
>>> for first, last in name_list:
        names.setdefault('first', []).append(first)
        names.setdefault('last', []).append(last)
>>> print names
{'first': ['Jon', 'Jeff', 'Joel'], 'last': ['Skeet', 'Atwood', 'Spolsky']}

setdefault returns the existing value if the key already exists in dict, or sets the new value and returns the newly set value if the key doesn't exist.



回答3:

Have a look at collections.defaultdict. Then you can do things like:

from collections import defaultdict

data['Names'] = defaultdict(list) # Or pass set instead of list.
data['Names']['first'].append("Bob")
data['Names']['first'].append("Jane")
data['Names']['last'].extend("T", "Mart")


回答4:

You should probably be storing the list of names as a list, rather than a dictionary. So you would have:

data['Names'] = {}
data['Names']['first'] = [] #note the brackets here instead of curlies
data['Names']['first'] = [value1, value2]

To add one after instantiation, you can do:

data['Names']['first'].append(another_first_name)

Lists are zero-indexed, so to get the 1st first name, you can say:

data['Names']['first'][0]