簡體   English   中英

使用 defaultdict 添加/更新 dict

[英]Adding/updating dict with defaultdict

我知道我可以執行以下操作來添加/更新 Python 字典中的鍵。

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

但是,對於我目前的情況,我試圖通過添加額外的 dict 來弄清楚如何使用此功能。 我已經完成了以下操作,但顯然沒有按預期工作。

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]
    }
}

好吧,現在您正嘗試將字典附加到 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]}})

當您嘗試添加其他 dict 時,您似乎混淆了 dict 和 list 操作。

關於您的代碼段的一些說明:

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)將不存在的條目設為 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]}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM