在Python中,调用字典通常有以下几种方法:
1. 使用方括号 `[]` 访问字典中的值:
```python
my_dict = {"name": "John", "age": 30}
print(my_dict["name"]) 输出:John
2. 使用 `get()` 方法访问字典中的值,如果键不存在则返回 `None`:
```python
my_dict = {"name": "John", "age": 30}
print(my_dict.get("name")) 输出:John
print(my_dict.get("city")) 输出:None
3. 使用 `in` 操作符检查键是否存在于字典中:
```python
my_dict = {"name": "John", "age": 30}
print("name" in my_dict) 输出:True
print("city" in my_dict) 输出:False
4. 使用 `for` 循环遍历字典的键或键值对:
```python
my_dict = {"name": "John", "age": 30, "city": "New York"}
for key in my_dict:
print(key, my_dict[key])
5. 使用 `items()`、`keys()` 和 `values()` 方法分别获取字典的所有键值对、键和值:
```python
my_dict = {"name": "John", "age": 30, "city": "New York"}
for key, value in my_dict.items():
print(key, value)
以上是调用字典的基本方法。