要從字典中讀取值,可以通過鍵來訪問對應的值。以下是一個簡單的示例:
# 創建一個字典
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
# 通過鍵訪問值
name = my_dict["name"]
age = my_dict["age"]
city = my_dict["city"]
print("Name:", name)
print("Age:", age)
print("City:", city)
輸出結果將會是:
Name: Alice
Age: 30
City: New York
另外,還可以使用 get()
方法來從字典中讀取值。如果鍵不存在,get()
方法會返回 None
或者指定的默認值。以下是一個示例:
# 創建一個字典
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
# 使用 get() 方法訪問值
name = my_dict.get("name")
gender = my_dict.get("gender", "Unknown")
print("Name:", name)
print("Gender:", gender)
輸出結果將會是:
Name: Alice
Gender: Unknown