python的数据结构之一
字典 -- dict
定义:
dic = {"key":"value"} -- 键值对
字典的作用:
存储数据,大大量,将数据和数据起到关联作用
dic = {"10":"苹果手机",
"11":"苹果手机",
15:"小米手机",
15:"华为手机",
(1,):"oppo手机",
}
print(dic)
所有的操作都是通过键
键:必须是不可变的数据类型(可哈希),且唯一 不可哈希就是可变数据类型
值:任意
字典是可变数据类型,无序的
字典的增:
1.暴力添加:
dic["日阳"] = "曹洋" # 字典的添加,添加的是一个键值对
dic["小妹"] = ["听歌","唱歌","吃","烤馕","大盘鸡","葡萄干"]
print(dic)
dic = {
"日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
"炮手":"飞机",
"豹哥":"贴膏药",
"宝元":"宝剑",
"alex":"吹牛逼"
}
2.有则不添加,无则添加
dic.setdefault("元宝",["唱","跳","篮球","喝酒"])
print(dic)
setdefault 分为两步:
1,先查看键是否在字典
2,不存在的时候进行添加
print(dic.setdefault("元宝"))
字典的删除:
dic = {
"日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
"炮手":"飞机",
"豹哥":"贴膏药",
"宝元":"宝剑",
"alex":"吹牛逼"
}
print(dic.pop("宝元")) #pop删除通过字典中的键进线删除 返回的也是被删除的值
print(dic)
dic.clear() # 清空
print(dic)
del dic # 删除的是整个容器
print(dic)
del dic["alex"] # 通过键进行删除
print(dic)
字典中是没有remove *****
字典的改:
dic = {
"日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
"炮手":"飞机",
"豹哥":"贴膏药",
"宝元":"宝剑",
"alex":"吹牛逼"
}
dic["alex"] = "dsb" # 有则就覆盖,没有添加
print(dic)
#
dic1 = {"alex":"上过北大","wusir":"干过前端"}
dic1.update(dic)
print(dic1)
字典的查:
dic = {
"日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
"炮手":"飞机",
"豹哥":"贴膏药",
"宝元":"宝剑",
"alex":"吹牛逼"
}
print(dic.get("alex")) # 查询不到返回None
print(dic.get("元宝","找不到啊")) # 查找不到的时候返回自己制定的内容
print(dic.setdefault("alex")) # 查询不到返回None
print(dic["alex"]) # 查询不到就报错了
for i in dic: # 查看所有的键
print(i)
for i in dic: # 查看所有的值
print(dic.get(i))
print(dic.keys()) # 获取到的是一个高仿列表
print(dic.values()) # 获取到的是一个高仿列表
for i in dic.values(): # 高仿列表支持迭代
print(i)
print(dic.values()[3]) 高仿列表不支持索引
lst = []
for i in dic:
lst.append(dic[i])
print(lst)
print(list(dic.values()))
lst = []
for i in dic:
lst.append((i,dic[i]))
print(lst)
print(list(dic.items()))
for i in dic:
print(i,dic[i])
for i in dic.items():
print(i[0],i[1])
解构:
面试题:
a = 10
b = 20
a,b = b,a
print(a)
print(b)
a,b = 10,20
print(a)
print(b)
a = 10,20
print(a)
print(10,20)
a,b = (1,20)
print(a)
print(b)
a,b = [11,20]
print(a)
print(b)
a,b = "wc"
print(a)
print(b)
dic = {"key1":2,"key2":4}
a,b = dic
print(a)
print(b)
解构的作用,
lst = [1,2,3,4,5,6,7,8]
lst1 = lst[:2] # 两个都是列表的时候才能够相加
lst1.append(lst[4])
for i in lst1:
print(i)
print(lst[:2] + list(str(lst[4])))
lst = [1,2,3,4,5,6,7,8]
a,b,c,d,e,*aa = lst # *是万能接受
print(a,b,e)
for i in dic.items():
a,b = i
print(a)
print(b)
for i in dic.items():
a,b = i # 自己写的解构
print(a)
print(b)
for a,b in dic.items():
print(a)
print(b)