字典
字典属于无序序列,元素存放无序,是通过哈希方式进行数据存取的,字典是一个可变容器,字典中保存一个个的键值对: key : value。我们通过key来获取对应的值,很类似我们的汉语字典。
1.字典中键必须是唯一的,必须是不可变类型
2.字典查找速度比较快
字典:key:value {key:value, key1:value1}
键必须是不可修改的元素
键不能重复,如果有重复,后面增加的键值对会覆盖前面的键值对
字典的创建
d1 = {} #空字典
d1 = dict() #空字典
d2 = {'name':'麻辣大虾','taste':'美味'}
d3 = dict(a=1,b=2)
d4 = dict([('a', 1),('b', 2)])
d5 = dict({'a':1,'b':2})
字典操作
1.元素访问
#获取 语法:字典名[key]
print(dict1["hanmeimei"])
#print(dict1["tom"]) #KeyError: 'tom'
#字典名.get()
result = dict1.get("lilei",'1') # 如果没有lilei这个键,返回默认值1,不会报错
print(result)
2.添加:当指定的键不存在的时候,则表示添加
dict1["tom"] = 70
print(dict1)
#但是,如果键已经存在,则表示修改value
dict1["jack"] = 50
print(dict1)
3. 删除 pop 删除并返回指定键对应的值
#注意:通过键,直接删除整个键值对
dict1.pop("jack")
print(dict1)
del dict1['lilei'] #删除键值对,不返回值
dict1.clear() #清空字典
del dict1 #删除整个字典
4. 字典合并
a = {1:'hello'}
b = {2:'world'}
a.update(b)
print(a)
5.字典遍历
d1 = {'name':'三傻子','age':20}
d2 = {} # 空字典
d3 = dict([(1,2),(3,4)])
遍历所有的键
print(d1.keys()) # 获取字典的所有键
print(list(d1.keys()))
for key in d1.keys():
print(key)
遍历所有的值
print(d1.values(),list(d1.values()))
for value in d1.values():
print(value)
遍历所有的值和键
#items,得到的结果是一个列表,列表中的元素是元组
print(d1.items())
for key,value in d1.items():
print(key,value)
for index,key in enumerate(dict2):
value = dict2[key]
print(index,key,value)
6.获取键值对的个数
print(len(dict1))
7.成员操作
d2 = {'name':'麻辣⻰虾','taste':'美味'}
print('name' in d2) #判断某个键是否在列表中
字典的增删改查
d1 = {‘name’:‘三傻子’,‘age’:20}
d2 = {} # 空字典
d3 = dict([(1,2),(3,4)])
增加
d1.setdefault('sex','男')
print(d1)
删除
d1.pop('age')
del d1['age']
修改
修改值, 如果字典里没有该键值对,就会增加一个键值对
d1['age'] = 30
print(d1)
查找
print(d1.items(),type(d1.items()))
#print(list(d1.items()))
for key,value in d1.items():
print(key,value)
zip函数
zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个元组,然后返回由这些元组组成的列表。
如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同。
语法:zip(iterable1,iterable2, …)
参数说明:iterable – 一个或多个可迭代对象(字符串、列表、元祖、字典)
a = [1,2,3,4]
b = [2,3,4]
res = zip(a,b)
print(list(res)) #[(1, 2), (2, 3), (3, 4)]
#可以使用for-in 遍历
for x,y in zip(a,b):
print(x,y)
zip可以把列表和元祖的第一个元素,压成字典
dict可以压缩成字典
a = [1,2,3,4]
b = (20,30,40,40,50)
c = (10,20,30)
res = zip(a,b,c)
print(list(res))#[(1,20,10),(2,30,10),(3,40,30)]
print(res)#<zip object at 0x000000000223D9C8>
for value in res:
print(value)
#(1, 20, 10)
#(2, 30, 20)
#(3, 40, 30)
构建字典
res = dict(zip(a,b))
print(res)#{1: 20, 2: 30, 3: 40, 4: 40}
collections模块下的工具类
"""
找出序列中出现次数最多的元素
"""
from collections import Counter
words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around',
'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes',
'look', 'into', 'my', 'eyes', "you're", 'under'
]
counter = Counter(words)
print(counter.most_common(3))
深拷贝和浅拷贝
元素分类:
不可变对象:int、flfloat、bool、tuple、str
可变对象:list、dict、set
可变对象没有深拷贝和浅拷贝的说法,不会产生副本
可变对象:列表、字典和集合
浅拷贝:只复制容器,不复制容器中元素
深拷贝:复制容器,如果容器中元素是可变的,元素也发生复制
深复制和浅复制
import copy
#不可变对象:int float boolean str,tuple,
#1.不可变对象不存在深考本和浅拷贝
#a = 10
#b = a
#copy是浅拷贝
#c = copy.copy(a)
#print(id(a),id(b),id(c)) #1766223152 1766223152 1766223152
#s1 = "ok"
#s2 = copy.copy(s1)
#print(id(s1),id(s2)) #31192320 31192320
#可变对象,list,dict set 容器
#a = [1,[5,6],3]
#浅拷贝 只拷贝容器,不拷贝元素
#b = copy.copy(a)
##print(id(a),id(b)) #42443848 42444040
#b[0] = 10
#print(a,b)
#print(id(a[1]),id(b[1])) #36152392 36152392
深拷贝 ,既复制容器也复制元素(元素必须是可变对象)
a = [1,[5,6],3]
b = copy.copy(a)
c = copy.deepcopy(a)
print("a:",id(a),[id(x) for x in a])
print("b:",id(b),[id(x) for x in b])
print("c:",id(c),[id(x) for x in c])
"""
a: 42374664 [1766222864, 42374472, 1766222928]
c: 42375944 [1766222864, 42375880, 1766222928]
"""
a[0] = 10
#print(c) #[1, [5, 6], 3]
a[1][0]= 15
print(a)
print(b)
print(c)
字典推导式
d1 ={key:v for key,v in zip(['name','age'],['tom',20])}
print(d1)#{'name': 'tom', 'age': 20}
d2 = {'hero':'老板','life':100,'attack':100}
print({v:key for key,v in d2.items()})
#{'老板': 'hero', 100: 'attack'}
用字典记录字符串出现的元素的次数
s = ‘sdklfklsdljwoeirioewiojdsgklsdlkf’
fq = {ch:s.count(ch) for ch in set(s)}
print(fq)
#{‘e’: 2, ‘r’: 1, ‘j’: 2, ‘k’: 4, ‘w’: 2, ‘o’: 3, ‘f’: 2, ‘d’: 4, ‘s’: 4, ‘g’: 1, ‘i’: 3, ‘l’: 5}
Counter 统计元素频率
from collections import Counter
fq = Counter(s)#返回字典,字典的键就是元素,元素出现的次数是值
print(fq.most_common(2))#返回次数最大的2个键值对
#[(‘l’, 5), (‘s’, 4)]