Python:存储与字典中的键相关联的列表值

csg*_*y11 1 python information-retrieval

我知道python词典如何存储键:值元组.在我正在进行的项目中,我需要存储与列表值相关联的密钥.ex:key - > [0,2,4,5,8]其中,key是来自文本文件的单词,list值包含代表发生单词的DocID的int.

一旦我在另一个文档中找到相同的单词,我需要将该DocID附加到列表中.

我怎样才能做到这一点?

Vin*_*vic 6

您可以使用defauldict,如下所示:

>>> import collections
>>> d = collections.defaultdict(list)
>>> d['foo'].append(9)
>>> d
defaultdict(<type 'list'>, {'foo': [9]})
>>> d['foo'].append(90)
>>> d
defaultdict(<type 'list'>, {'foo': [9, 90]})
>>> d['bar'].append(5)
>>> d
defaultdict(<type 'list'>, {'foo': [9, 90], 'bar': [5]})
Run Code Online (Sandbox Code Playgroud)