Python dictionaries. How to save a new value from overwriting the previous value?

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

so here is my problem:

When I add a name to the dictionary, I proceed to add a second through the function, the previous name is overwritten by the last. How do I fix this? I know that it includes something like a dictionary in a dictionary or nested conventions. Here is my code:

def store(data,value):
    data['Names'] = {}
    data['Names']['first'] = {}
    data['Names']['first'] = {value}
+3
source share
4 answers

Turn data['Names']['first']in the list and add to it:

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

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

Python < 2.5 defaultdict, dict .

>>> 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 , dict , .

+2

Take 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")
+1
source

You should probably store the list of names as a list, not a dictionary. So you will have:

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

To add one after creating the instance, you can do:

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

Lists are indexed with a zero mark, so to get the first name you can say:

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

Source: https://habr.com/ru/post/1788774/


All Articles