Start learning free

LESSON 59 OF 66 · NOSQL: REDIS

Keys and Values

Practice

Redis is a database that keeps its data in memory. It works like one big Python dict: every value is stored under a name, its key. There are no tables and no SQL. Instead of a SELECT … WHERE, you ask for a key and get its value back. In this lesson your code talks to an in-memory Redis that starts empty. The same code runs unchanged on a real Redis server.

Five calls: r.set(key, value) stores a value and r.get(key) reads it back. A key that was never set gives None, not an error, like a SELECT that finds no row. r.incr(key) adds 1 to a number and gives back the new number. r.delete(key) removes a key, and r.exists(key) tells you how many of the keys you name are there.

r.set("city", "Lisbon")
print(r.get("city"))       # Lisbon
print(r.get("country"))    # None
print(r.incr("likes"))     # 1: a missing key starts at 0

One surprise: Redis keeps every value as text. You can store the number 41, but r.get gives back the string '41'. r.incr still works, because Redis reads the text as a number, adds 1 and stores the result.

The starting code connects to Redis as r and sets "visits" to 41. Your program must print:

Name: Corner Shop
Phone: None
Visits: 42
Stored: '42'
Exists: 0

Your task: store the shop's name under "shop:name" and read it back, read the missing key "shop:phone", add 1 to "visits", show what get really gives back for it, then delete the name and check that it is gone.


Assignment
Follow the Coding Tutorial to store, read, count and delete keys in Redis, one line at a time.


Hint
Wrap a value in repr(...) to see the quotes that show it is a string. A key that isn't there gives None from get and 0 from exists.


STEP 1 OF 7
    Ctrl + Enter to check