Python dictionaries-How to keep the new value from

2020-02-14 08:34发布

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}

4条回答
ゆ 、 Hurt°
2楼-- · 2020-02-14 09:07

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")
查看更多
乱世女痞
3楼-- · 2020-02-14 09:12

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.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-02-14 09:18

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]
查看更多
做个烂人
5楼-- · 2020-02-14 09:29

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)
查看更多
登录 后发表回答