Skip to content

Step 1 of 3 · Reading · ~2 min

Hash Maps

Hashes

Hashes: a map inside a key

So far every key has held one value (string, or a whole list). A Redis hash is a nested structure: one key contains an entire field → value dictionary, like a mini object. user:1001 might hold {name: "Alice", age: "30", email: "..."} all under one key — that's the classic use case for modeling records without a full separate table per field.

The natural structure: a dict of dicts

python

zip(it, it) is a compact idiom for walking a flat list two-at-a-time — it consumes the same iterator twice, so each call to next() advances it, pairing element 0 with 1, then 2 with 3, and so on. It's a clean way to turn ["name", "Alice", "age", "30"] into [("name", "Alice"), ("age", "30")] without manual index arithmetic.

Why HSET's return value is easy to get wrong

HSET returns the count of newly created fields, not the total number of field/value pairs given in the command. If user:1001 already has a name field and you run HSET user:1001 name Bob age 30, the reply is :1\r\n — only age is new; name was updated, not added. Check membership in the hash before you overwrite the value, or you'll always report the field as new.

HGET

python

Both "the key doesn't exist" and "the key exists but lacks this field" collapse to the same nil reply ($-1\r\n) — a client can't distinguish "no hash here" from "hash exists, wrong field name" from the reply alone, and that's exactly how real Redis behaves too.

Type checking

If key already holds a string or a list (i.e. it appears in one of your other type-specific dicts), HSET/HGET must refuse with:

-WRONGTYPE Operation against a key holding the wrong kind of value\r\n

This is the same check you wrote for lists — factor it into one type_check(key, target_dict) helper shared across all your data-type commands so type safety is enforced consistently instead of copy-pasted per command.

Where this is heading

Hashes are the foundation for HGETALL, HDEL, HEXISTS, and HLEN in the next lesson, and conceptually they're what backs Redis's use as a session store or object cache in real systems — one HSET per field update instead of round-tripping a whole serialized blob.

Up nextHDEL & HGETALL — Managing HashesHashes

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…