開始使用免費開始

使用 Redis 擷取鍵值資料

既然你已經練習用 Redis 和 Python 來儲存鍵值配對,現在來探索這個流程的另一半:擷取鍵值配對。本例中,你會練習擷取幾組不同的鍵值配對,這些配對可能出現在用來回報天氣資料的網路應用程式中。

我們已經建立好連線物件,並存放在變數 redis_conn 中。開始吧!

本練習屬於課程

NoSQL 入門

檢視課程

練習說明

  • 使用變數 redis_conn 與適當的方法,從 Redis 嘗試解析 cities 清單中每個 city 的溫度。
  • 如果傳入的 key 其 temperature 值為 None,就將該 key 的值設為 "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}")
編輯並執行程式碼