要从字典中读取值,可以通过键来访问对应的值。以下是一个简单的示例:
# 创建一个字典 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