How to Use Redis HSET and HGET in Python

This code demonstrates how to store and retrieve hash data in Redis using Python's redis library with HSET, HGET, HGETALL, and HDEL commands.

Easy Python 3.6+ Aug 9, 2026 Caching & Redis 12 views 0 copies

Requires third-party packages — install first
pip install redis

Python code

27 lines
Python 3.6+
import redis

# Connect to Redis (adjust host/port as needed)
r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)

# Clear any existing data for demonstration
r.delete('user:1')

# HSET - Store a hash
r.hset('user:1', mapping={'name': 'Alice', 'age': 30, 'city': 'New York'})

# HGET - Retrieve a single field
print("Name:", r.hget('user:1', 'name'))

# HGETALL - Retrieve all fields
print("All fields:", r.hgetall('user:1'))

# Update an existing field
r.hset('user:1', 'age', 31)
print("Updated age:", r.hget('user:1', 'age'))

# Delete a field
r.hdel('user:1', 'city')
print("After deletion:", r.hgetall('user:1'))

# Close connection
r.close()

Output

stdout
Name: Alice
All fields: {'name': 'Alice', 'age': '30', 'city': 'New York'}
Updated age: 31
After deletion: {'name': 'Alice', 'age': '31'}

How it works

The decode_responses=True parameter ensures that Redis returns strings instead of bytes, making output more readable. hset can store multiple fields via the mapping parameter or a single field when given key-value arguments. hget retrieves a specific field's value, while hgetall returns all fields as a dictionary. The hdel command removes specified fields from the hash. The connection is closed at the end to free resources.

Common mistakes

  • Forgetting to set `decode_responses=True` can lead to byte-string outputs that are hard to read.
  • Using `hget` on a non-existent field or key returns `None`; ensure the field exists before expecting a value.
  • Neglecting to close the Redis connection can cause resource leaks in long-running applications.

Variations

  1. Use `hmset` (deprecated) or `hset` with a dictionary for setting multiple fields at once.
  2. Use `hgetall` followed by dictionary methods to process all fields efficiently.

Real-world use cases

  • Caching user profiles with fields like name, email, and preferences for fast retrieval.
  • Storing session data as hashes with attributes such as user ID and last activity.
  • Maintaining product attributes in Redis for e-commerce workspaces to speed up lookups.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Caching & Redis

Related tutorials and quizzes for this topic.