使用 Redis 检索键值数据
您已经练习了用 Redis 和 Python 存储键值对,接下来来完成这一步的另一半:检索键值对。本例中,您将练习检索几个可能出现在用于天气数据报表的 Web 应用中的键值对。
我们已创建连接对象并存放在变量 redis_conn 中。祝您练习顺利!
本练习是课程的一部分
NoSQL 入门
练习说明
- 使用变量
redis_conn和合适的方法,从 Redis 中尝试解析列表cities中每个city的温度。 - 如果传入键对应的
temperature值为None,则将该键的值设置为"unknown temperature",并打印一条简短消息。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Loop through each of the cities
for city in cities:
# Grab the temperature
temperature = ____.___(f"{city}_temp")
# Check if the temperature is None
if temperature is None:
# Store an unknown temperature
____.____(f"{city}_temp", "unknown temperature")
print(f"Unknown temperature in {city}")
else:
# Otherwise, print the temperature
print(f"The temperature in {city} is {temperature}")