# 1. 字典的定义
# 定义字典的字面量
# {key: value, key: value, ......, key: value}
# 定义字典变量
# my_dict = {key: value, key: value, ......, key: value}
# 定义空字典
# my_dict = {}
# my_dict = dict()
定义重复Key的字典
my_dict1 = {"张三": 18, "李四": 19, "张三": 20}
print(my_dict1)
从上述可以看出,字典中不允许重复的Key,如果有重复的Key,则会输出后面的。
# 2. 从字典中获取数据
# 字典同集合一样,不能通过索引获取数据,但是字典可以通过 Key 值来取得对应的 value 值
my_dict2 = {"张三": 18, "李四": 19, "王五": 20}
print(my_dict2["张三"]) # 结果为18
print(my_dict2["李四"]) # 结果为19
print(my_dict2["王五"]) # 结果为20
# 3. 字典的嵌套
my_dict3 = {
"张三": {"age": 18, "gender": "男"},
"李四": {"age": 19, "gender": "男"},
"王五": {"age": 20, "gender": "男"}
}
print(my_dict3["张三"]["age"]) # 结果为18
print(my_dict3["李四"]["gender"]) # 结果为男
print(my_dict3["王五"]["age"]) # 结果为20
# 语法: 字典[key] = value
my_dict4 = {"张三": 18, "李四": 19, "王五": 20}
my_dict4["赵六"] = 21
print(my_dict4) # {"张三": 18, "李四": 19, "王五": 20, "赵六": 21}
# 语法: 字典[key] = value
my_dict5 = {"张三": 18, "李四": 19, "王五": 20}
my_dict5["张三"] = 22
print(my_dict5) # {"张三": 22, "李四": 19, "王五": 20}
注意:字典中的Key不能重复,如果Key不存在则是新增,如果存在,则是更新
# 语法: 字典.pop(key) => 结果:获得指定Key的value值,并从字典中删除该元素
my_dict6 = {"张三": 18, "李四": 19, "王五": 20}
my_dict6.pop("李四")
# print(my_dict6.pop("李四")) # 19
print(my_dict6) # {"张三": 18, "王五": 20}
# 语法: 字典.clear()
my_dict7 = {"张三": 18, "李四": 19, "王五": 20}
my_dict7.clear()
print(my_dict7) # 结果为{}
# 语法: 字典.keys()
my_dict8 = {"张三": 18, "李四": 19, "王五": 20}
keys = my_dict8.keys()
print(keys) # dict_keys(['张三', '李四', '王五'])
获取所有的values
print(my_dict8.values()) # dict_values([18, 19, 20])
方式1:通过获取到全部的key来进行遍历
for key in keys:
print(key)
print(my_dict8[key])
print("----------------------")
方式2:直接对字典进行for循环
# 直接对字典进行for循环, 每一次循环都是直接得到key
for key in my_dict8:
print(key)
print(my_dict8[key])
print("----------------------")
num = len(my_dict8)
print(num) # 3