python遍历字典中的某个键
时间: 2023-12-29 10:49:27 浏览: 33
可以使用字典的get方法,例如:
```python
my_dict = {"name": "Alice", "age": 25, "gender": "female"}
age = my_dict.get("age")
print(age) # 输出 25
```
如果键不存在,则返回None。也可以在get方法中指定一个默认值,如果键不存在则返回该默认值。
```python
my_dict = {"name": "Alice", "gender": "female"}
age = my_dict.get("age", 18)
print(age) # 输出 18,因为键"age"不存在
```
相关问题
python遍历多重字典
遍历多重字典需要嵌套循环,示例代码如下:
```python
my_dict = {"person1": {"name": "Alice", "age": 25, "city": "New York"},
"person2": {"name": "Bob", "age": 30, "city": "Los Angeles"}}
# 遍历多重字典的键值对
for person, info in my_dict.items():
print(person)
for key, value in info.items():
print("\t", key, value)
```
输出:
```
person1
name Alice
age 25
city New York
person2
name Bob
age 30
city Los Angeles
```
另外,如果需要在循环中获取多重字典的某个特定键的值,可以使用字典的索引方式,示例代码如下:
```python
# 获取 person1 的城市
city = my_dict["person1"]["city"]
print(city)
```
输出:
```
New York
```
遍历字典判断某个值是否存在
可以使用 `in` 关键字来判断某个值是否存在于字典中。示例如下:
```python
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
if "Alice" in my_dict.values():
print("Alice exists in the dictionary")
if "gender" not in my_dict:
print("gender does not exist in the dictionary")
```
输出:
```
Alice exists in the dictionary
gender does not exist in the dictionary
```
在第一个 `if` 语句中,我们使用了 `in` 关键字来判断是否存在值为 "Alice" 的键值对,由于存在,所以输出了 "Alice exists in the dictionary"。
在第二个 `if` 语句中,我们使用了 `not in` 关键字来判断是否存在键名为 "gender" 的键值对,由于不存在,所以输出了 "gender does not exist in the dictionary"。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)