1---字典的创建
(1){ }---创建空字典
(2)dict(zip())---通过映射函数创建字典
tt2=["hello","python","byte"]
tt3=["12",'22',"29"]
tt4=dict(zip(tt2,tt3))
print(tt4)
###{'hello': '12', 'python': '22', 'byte': '29'}
###相当于tt2是键 tt3是值
(3)
ts = dict(ji ="激活卡", ok = '网')
###注意:这个键不能是数字
print(ts)
###{'ji': '激活卡', 'ok': '网'}
(4)创建值为空的字典
name_list=["hello","python"]
keyss=dict.fromkeys(name_list)
### fromkeys()创建值为空的字典
print(keyss)
###{'hello': None, 'python': None}
(5)一个元组一个列表组成字典
tt2 = ("hello", "python", "byte")
tt3 = ["12", '22', "29"]
print({tt2:tt3})
###一个列表一个元组组成字典用{tt2:tt3}
### {('hello', 'python', 'byte'): ['12', '22', '29']}
2---删除
(1)del
tt2 = ("hello", "python", "byte")
tt3 = ["12", '22', "29"]
tt4 = dict(zip(tt2, tt3))
del tt4["byte"]
###删除 删除字典中的指定元素的键
print(tt4)
###{'hello': 'world', 'python': '22'}
(2) clear()---清除字典中的所有元素
3---访问字典键的值
(1) get() ()里面的是键
tt2 = ("hello", "python", "byte")
tt3 = ["12", '22', "29"]
tt4 = dict(zip(tt2, tt3))
tt4=tt4.get("python")
print(tt4)
### 22
(2)[ ] [ " "]里面是键
tt2 = ("hello", "python", "byte")
tt3 = ["12", '22', "29"]
tt4 = dict(zip(tt2, tt3))
tt5=tt4["hello"]
print(tt5)
### 12
4--遍历字典
items()--获取字典中的键值对
keys()--获取字典中的键
values()--获取字典中的值
tt2 = ("hello", "python", "byte")
tt3 = ["12", '22', "29"]
tt4 = dict(zip(tt2, tt3))
for item in tt4.items():
###通过 items() 获取键值对
print(item)
### ('hello', '12')
### ('python', '22')
### ('byte', '29')
for key,value in tt4.items():
print(key,value)
### hello 12
### python 22
### byte 29
5--添加、修改字典元素
tt2 = ("hello", "python", "byte")
tt3 = ["12", '22', "29"]
tt4['hello']='world'
###修改
###{'hello': 'world', 'python': '22', 'byte': '29'}
tt4['ooo']='title'
###添加
### {'hello': 'world', 'python': '22', 'byte': '29', 'ooo': 'title'}
print(tt4)
6---字典推导式
tt2 = ("hello", "python")
tt3 = ["12", '22', "29"]
tt4 = dict(zip(tt2, tt3))
tt5={i:random.randint(10,100) for i in range(1,5)}
### i相当于键
print(tt5)
### {1: 74, 2: 34, 3: 21, 4: 79}