Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Storing a list value associated with a key in dictionary

I know how python dictionaries store key: value tuples. In the project I'm working on, I'm required to store key associated with a value that's a list. ex: key -> [0,2,4,5,8] where, key is a word from text file the list value contains ints that stand for the DocIDs in which the word occurs.

as soon as I find the same word in another doc, i need to append that DocID to the list.

How can I achieve this?

like image 707
csguy11 Avatar asked May 29 '26 11:05

csguy11


1 Answers

You can use defauldict, like this:

>>> 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]})
like image 134
Vinko Vrsalovic Avatar answered Jun 01 '26 02:06

Vinko Vrsalovic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!