Python hash table design

I want to implement a hash table in python. In the table, the class object will be associated with the key value. The problem is that 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 should I do if I want to sort a table using a specific class value.

For example, consider we have three values: document_id, score, and rank. There is a class โ€œdocumentโ€, which consists of โ€œratingโ€ and โ€œrankโ€. "document_id" will be the key element of the table.

I want to update the "rating" of various table entries using the key: "document_id". But when updating the results is complete, I want to sort the list / table using the rating and assign the rank value to the "rank" variable based on the updated rating.

Can someone kindly give me some recommendations on how I can proceed? Or maybe I just need to make a list?

The maximum number of table elements can be up to 25000-30000.

Thanks.

+6
source share
3 answers

The Python dict is already a hash table.

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

To assign a rank:

 docs = sorted(doc_hash.itervalues(), key=operator.attrgetter('score'), reverse=True) for i, doc in enumerate(docs): doc.rank = i 
+21
source

Why not use an 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)]) 
+4
source

Something like that?

 sorted_keys = sorted(d.keys(), key=lambda element: element['score']) for i in range(len(sorted_keys)): d[sorted_keys[i]]['rank'] = i 

assigns each element in d (elements are also implied as dictionaries) a rank based on its rating.

0
source

Source: https://habr.com/ru/post/908043/


All Articles