Добавление / обновление dict с defaultdict - PullRequest
0 голосов
/ 09 марта 2020

Я знаю, что могу сделать следующее, чтобы добавить / обновить ключ в словаре в Python.

from collections import defaultdict
mydict = defaultdict(list)
mydict[x].append(y)

Однако в моей текущей ситуации я пытаюсь выяснить, как использовать эта функциональность, добавив дополнительный дикт. Я сделал следующее, но, очевидно, он работает не так, как задумано.

mydict[x].append({'newKey': []})
mydict[x]['newKey'].append(100)

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    mydict[x]['newKey'].append(100)
TypeError: list indices must be integers or slices, not str

Есть ли хороший способ использовать defaultdict, чтобы в итоге получить словарь, подобный этому, и постоянно добавлять к newKey ?:

{
    x: {
        'newKey': [100]
    }
}

Ответы [ 2 ]

1 голос
/ 09 марта 2020

Вы, кажется, путаете манипуляции с диктом и списком, когда пытаетесь добавить свой дополнительный диктат.

Некоторые пояснения по поводу вашего фрагмента:

from collections import defaultdict
mydict = defaultdict(list)
x = 'x'
y = 'bar'
# getting mydict's field 'x'. As it does not exists, and 
# mydict is a default dict, this will create a key 'x' mapped 
# to the value [] and return it
mydict[x]
# so we retrieve the list mydict created for us and we add an element
# inside. Note that we're inserting y into a list
mydict[x].append(y)
# getting the same list and insterting another element inside
# mydict:
# {
# 'x' : ['bar', {'newKey': []}]
# }
mydict[x].append({'newKey': []})
# ...and that's why the following command will not work
mydict['x']['newKey'] # ERROR: mydict['x'] is a list and not a dict

Возможно, вы сами все это поняли. Теперь пришло время для предложений по ее решению:

  • используйте defaultdict(dict), чтобы иметь возможность диктовать несуществующие записи вместо списков
  • использовать более сложный метод инициализации:
def init_entry():
    return {'newKey': [100]}
mydict = defaultdict(init_entry)
mydict['x']['newKey'].append(24)
mydict['y']['newKey'].append(37)
print(mydict)
#  {'x': {'newKey': [100, 24]}, 'y': {'newKey': [100, 37]}}

1 голос
/ 09 марта 2020

Ну, сейчас вы пытаетесь добавить словарь к mydict, так что, похоже, вы должны использовать mydict = defaultdict(dict)

Тогда вы можете делать то, что пытались:

In [2]: mydict = defaultdict(dict)
In [4]: mydict['x'] = {'newKey': []}

In [5]: mydict
Out[5]: defaultdict(dict, {'x': {'newKey': []}})

In [7]: mydict['x']['newKey'].append(100)

In [8]: mydict
Out[8]: defaultdict(dict, {'x': {'newKey': [100]}})
...