Redis: hset with ‘items’ parameter

In Python, Redis.hset function has ‘items’ that, per documentation
“accepts a list of key/value pairs that will be added to hash “name“.”.

You would think that it’s something like [("key1", "value1"), ("key2"), ("value2")]?
Wrong!

It’s ["key1", "value1", "key2", "value2"].

So much for “key-value pairs”. If you give it an odd number of elements, it barfs with "redis.exceptions.ResponseError: wrong number of arguments for 'hset' command".

The items parameter seems to be a foster child of the hset method. Google AI was unable to give me a usage example: I mean, it of course said “here is an example using the items parameter”, but the example itself did not contain the word ‘item’. ChatGPT claimed that ‘items’ must be an old deprecated parameter name or a confusion with dict.items(). Anyway, here’s a working piece of code:

import redis

r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)
r.hset("country:42", items=["language", "Flemish", "capital", "Brussels"])

Leave a Reply

Your email address will not be published. Required fields are marked *