Python 字典的 items()
方法是一个非常重要的内置方法,用于获取字典中所有键值对的动态视图。以下是详细的技术解析:
一、案例1:字典遍历
config = {'host': 'localhost', 'port': 8080}
for param, value in config.items():
print(f"Setting {param} to {value}")
二、案例2:快速字典转换
# 检查所有值是否大于零
data = {'x': 5, 'y': -2}
if all(v > 0 for _, v in data.items()):
print("All values valid")
三、案例3: 转换为列表
scores = {
"Math": 90,
"English": 85,
"Science": 92
}
# 将字典的键值对转换为列表
score_list = list(scores.items())
print(score_list) # 输出:[('Math', 90), ('English', 85), ('Science', 92)]