在Python里,我们把对象称为字典
1、for循环遍历字典, 默认获取的是key
my_dict = {'bookName': 'python', 'price': 100}
for key in my_dict:
print(key)
# 输出
>> bookName
>> price
2、根据key获取value值
my_dict = {'bookName': 'python', 'price': 100}
for key in my_dict:
value = my_dict[key]
print(key, value)
# 输出
>> bookName python
>> price 100
3、遍历字典中的每一个value
my_dict = {'bookName': 'python', 'price': 100}
for key in my_dict.values():
print(key)
# 输出
>> python
>> 100
4、遍历字典中的每项数据,并且把键值对封装到元祖里面
my_dict = {'bookName': 'python', 'price': 100}
for key in my_dict.items():
print(key)
# 输出
>> ('bookName', 'python')
>> ('price', 100)
5、利用拆包,使不同的变量保存在容器类型中
my_dict = {'bookName': 'python', 'price': 100}
for key, value in my_dict.items():
print(key, value)
# 输出
>> bookName python
>> price 100