""""基本数据类型(dict)"""
已知的可哈希(不可变)的数据类型: int, str, tuple, bool
不可哈希(可变)的数据类型: list, dict, set
语法 :
{key1: value1, key2: value2. }
注意: key必须是不可变(可哈希)的. value没有要求.可以保存任意类型的数据
dic = {"电影":["无双","龙门飞甲",],"音乐":["陷阱","为你写诗"]}
print(dic["电影"])
print(dic["音乐"]) # 输出:["陷阱","为你写诗"]
"""1. 增加
如果dict中没有出现这个key, 就会新增一个 key:value 的组
"""
dic = {}
dic["name"] = "吴克群"
print(dic) # {'name': '吴克群'}
dic["age"] = 18
print(dic) #{'name': '吴克群', 'age': 18}
'''
.setdefault
如果dict中没有出现过这个 key:value. 可以通过setdefault设置默认值
'''
dic = {}
dic.setdefault("123")
print(dic) #{'123': None}
dic.setdefault("万达","王思聪")
print(dic) # {'123': None, '万达': '王思聪'}
""" 2.删除"""
dic = {"name":"Rox","hight":199}
a = dic.pop("name") # 被删除的
print(a) # Rox
dic.popitem()
print(dic) #{'name': 'Rox'} 随机删除的
dic.clear() # 清楚所有内容
print(dic) #输出空字典 {}
"""3.修改
.update() 更新
"""
dic = {"name":"Rox","hight":199}
dic1 = {"name":"Rox","hight":199,"age":33}
dic.update(dic1)
print(dic) # 把dic1的内容更新到 dic中
"""4. 查询"""
dic = {"name":"Rox","hight":199,"age":33}
print(dic["name"]) # Rox 如果查询的key不存在字典中会报错
print(dic[Rox]) # 这种会报错
print(dic.get("age")) # 33
print(dic.get(123)) # 查询不出 返回 None
print(dic.get("name","Rox")) # Rox
"""其他相关操作
.keys
.value
.items
"""
dic = {"name":"Rox","hight":199,"age":33,"love":"赵丽颖"}
print(dic.keys()) # dict_keys(['name', 'hight', 'age', 'love'])
print(dic.values()) # dict_values(['Rox', 199, 33, '赵丽颖'])
dic = {"name":"Rox","hight":199,"age":33,"love":"赵丽颖"}
print(dic.keys()) # 输出所有 的key
print(dic.values()) # 输出所有的 value
print(dic.items()) # 输出所有 key:value
"""" for 循环"""
dic = {"name":"Rox","hight":199,"age":33,"love":"赵丽颖"}
for key in dic.keys():
print(key) # 循环打印key
for value in dic.values():
print(value) # 循环打印value
for k,y in dic.items():
print(k,y) # 循环 打印 key 和 value
"""字典的嵌套"""
dic = {
"name": "詹姆斯",
"体重":"200斤",
"身高":"200cm",
"gfriend":{
"name1":"anba",
"name2":"lisa"
}
}
print(dic["name"])
print(dic["体重"])
print(dic.get("gfriend").get("name1")) # anba
print(dic.get("gfriend")) # {'name1': 'anba', 'name2': 'lisa'}