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