Start learning free

LESSON 61 OF 66 · NOSQL: REDIS

Hashes: A Small Record in Python

Practice

A plain Redis key holds one value, but a product has several: a name, a price, a stock. A hash keeps several fields under one key, like one row of a table: the key picks the row, and the fields are its columns. In this lesson your code talks to an in-memory Redis. The same code runs unchanged on a real Redis server.

Naming keys: Redis has no tables, so the key's name says what it holds: product:1 is product number 1, user:7 is user number 7. The calls: r.hset(key, mapping={...}) stores the fields of a dict, r.hget(key, field) reads one field, r.hgetall(key) reads them all as a dict, and r.hincrby(key, field, amount) adds to a number field.

r.hset("user:7", mapping={"name": "Ana", "city": "Lisbon", "points": 5})
print(r.hget("user:7", "city"))   # Lisbon
r.hincrby("user:7", "points", 3)
print(r.hgetall("user:7"))
# {'name': 'Ana', 'city': 'Lisbon', 'points': '8'}

As with plain keys, every value comes back as a string: the points are stored as text, and hgetall shows '8' after the increment. hincrby still works, because Redis reads the text as a number.

The starting code stores the Notebook as product:2. After your lines, the check prints the keys in Redis. The whole output must be:

Name: Mug
Mug: {'name': 'Mug', 'price': '12', 'stock': '9'}
Keys: ['product:1', 'product:2']

Your task: store the Mug as the hash "product:1" with name "Mug", price 12 and stock 10, print its name, take 1 off its stock after a sale, and print the whole record.


Assignment
Follow the Coding Tutorial to store a product as a hash, then read and change its fields, one line at a time.


Hint
mapping= takes a normal Python dict. A negative amount in r.hincrby takes away.


STEP 1 OF 4
    Ctrl + Enter to check

    Redis Hashes in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free