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.
- NLP | Storing Frequency Distribution in Redis
- NLP | Storing Conditional Frequency Distribution in Redis
- Scraping And Finding Ordered Words In A Dictionary using Python
- Program to print all distinct elements of a given integer array in Python | Ordered Dictionary
- NLP | How to score words with Execnet and Redis
- Python | Convert flattened dictionary into nested dictionary
- Python | Convert nested dictionary into flattened dictionary
- Python | Pretty Print a dictionary with dictionary value
- Python | Convert string dictionary to dictionary
- Python | Get the first key in dictionary
- Python | Get key from value in Dictionary
- Python Dictionary
- Add a key:value pair to dictionary in Python
- Python | Dictionary has_key()
- Python | Accessing Key-value in Dictionary
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.