NLP | Storing an ordered dictionary in Redis
An ordered dictionary is like a normal dict, but the keys are ordered by an ordering function. In the case of Redis, it supports ordered dictionaries whose keys are strings and whose values are floating point scores. This structure can come in handy in cases where information gain has to be calculated and all the words and scores have to be stored for later use.
The RedisOrderedDict class in rediscollections.py extends collections. MutableMapping to get a number of dict compatible methods for free. Then, it implements all the key methods that require Redis ordered set (also known as Zset) commands:
Code: Storing a frequency distribution in Redis.
Code : Creating an instance of RedisOrderedDict by passing in a Redis connection and a unique name
0 5.2000000000000002 1 [(b'bar', 5.2)]
Much of the code may look similar to the RedisHashMap, which is to be expected since they both extend collections.MutableMapping. The main difference here is that RedisOrderedSet orders keys by floating point values, and so it is not suited for arbitrary key-value storage like the RedisHashMap.
Outline explaining each key method and how they work with Redis:
- __len__(): This uses the zcard command to get the number of elements in the ordered set.
- __getitem__(): This uses the zscore command to get the score of a key, and returns 0 if the key does not exist.
- __setitem__(): This uses the zadd command to add a key to the ordered set with the given score, or updates the score if the key already exists.
- __delitem__(): This uses the zrem command to remove a key from the ordered set.
- keys(): This uses the zrevrange command to get all the keys in the ordered set, sorted by the highest score. It takes two optional keyword arguments, start and end, to more efficiently get a slice of the ordered keys.
Attention reader! Don’t stop learning now. Get hold of all the important Machine Learning Concepts with the Machine Learning Foundation Course at a student-friendly price and become industry ready.