Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python hash table design

Tags:

python

hash

I want to implement a hash table in python. On the table a class object will be associated with the key value. The problem is I want to use the key value to find the index of the class and update it (which of course is not a problem). But what can I do if I want to sort the table using a particular value of the class.

For example, let us consider, we have three value: document_id, score and rank. There is a class "document" which consists of "score" and "rank". "document_id" will be the key of the table.

I want to update the "score" of various entries of the table, using the key: "document_id". But when updating of the scores are done, I want to sort the list/table using the score and assign rank value to the "rank" variable based on updated score.

Can someone kindly give me some guideline about how can I proceed? Or maybe I should simply make it a list?

The maximum number of item of the table might be upto 25000-30000.

Thanks.

like image 230
Quazi Farhan Avatar asked Feb 09 '12 14:02

Quazi Farhan


2 Answers

Python's dict is already a hash table.

doc_hash = {}
doc_hash[doc.id] = doc

To assign rank:

docs = sorted(doc_hash.itervalues(), key=operator.attrgetter('score'), reverse=True)
for i, doc in enumerate(docs):
    doc.rank = i
like image 156
Ned Batchelder Avatar answered Sep 28 '22 07:09

Ned Batchelder


Why not use a OrderedDict?

>>> from collections import OrderedDict

>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}

>>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
like image 40
cha0site Avatar answered Sep 28 '22 07:09

cha0site