注意:字典和集合都是无序的,当要求数据有序时使用这两个要很小心。
创建字典
dict1 = {'李宁':'一切皆有可能','耐克':'just do it','阿迪达斯':'Impossible is nothing'}
print(dict1['李宁'])
dict2 = {0:'zero',1:'one',2:'two'}
print(dict2[0])
dict3 = dict((('zero',0),('one',1),('two',2)))
print(dict3)
dict4 = dict(李宁= '一切皆有可能',耐克 = 'just do it')
print(dict4)
dict4['李宁'] = '111'
print(dict4)
dict4['阿迪达斯'] = '2222'
print(dict4)
一切皆有可能
zero
{'zero': 0, 'one': 1, 'two': 2}
{'李宁': '一切皆有可能', '耐克': 'just do it'}
{'李宁': '111', '耐克': 'just do it'}
{'李宁': '111', '耐克': 'just do it', '阿迪达斯': '2222'}
字典常用函数
fromkeys
dict1 = {}
dict2 = dict1.fromkeys((1,2,3))
print(dict2) # {1: None, 2: None, 3: None}
dict2 = dict1.fromkeys((1,2,3),'number')
print(dict2) # {1: 'number', 2: 'number', 3: 'number'}
dict2 = dict1.fromkeys((1,2,3),('one','two','three'))
print(dict2) # {1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}
keys和values、items
dict1 = {}
dict1 = dict1.fromkeys(range(32),'赞')
for eachkey in dict1.keys():
print(eachkey) # 输出0-31
for eachvalue in dict1.values():
print(eachvalue) # 输出32个赞
for eachitem in dict1.items():
print(eachitem) # 输出(0, '赞')(1, '赞')(2, '赞')(3, '赞')(4, '赞')(5, '赞')...
get()
当索引在字典中不存在时,会报错,为了更好的表达,可以用get()函数
dict1 = {}
dict1 = dict1.fromkeys(range(32),'赞')
print(dict1.get(32)) # None
print(dict1.get(32,'木有')) # 木有
print(dict1.get(31,'木有')) # 赞
print(31 in dict1) # True
print(32 in dict1) # False
clear()函数:清空字典
dict1 = {1:'one'}
dict2 = dict1
dict1.clear()
print(dict2) #输出{}
dict1 = {1:'one'}
dict2 = dict1
dict1 = {}
print(dict2) #输出{1: 'one'}
copy():浅拷贝
dict1 = {1:'one'}
dict2 = dict1.copy()
dict3 = dict1
print(id(dict1),id(dict2),id(dict3)) #2575740008920 2575740008992 2575740008920
dict1[2] = 'two'
print(dict1) # {1: 'one', 2: 'two'}
print(dict2) # {1: 'one'}
print(dict3) # {1: 'one', 2: 'two'}
观察可以发现,直接赋值操作,两者指向的是同一片地址区域,当前者发生改变时后者也会变化,而浅拷贝不同。
pop和popitem
dict1 = {1:'one',3:'three',2:'two'}
print(dict1.pop(3)) # three
print(dict1) # {1: 'one', 2: 'two'}
print(dict1.popitem()) # (2, 'two') popitem随机弹出一项
print(dict1) # {1: 'one'}
setfalut()
dict1 = {1:'one',3:'three',2:'two'}
dict1.setdefault(4,'four')
print(dict1)
dict1.setdefault(5)
print(dict1)
#{1: 'one', 3: 'three', 2: 'two', 4: 'four'}
#{1: 'one', 3: 'three', 2: 'two', 4: 'four', 5: None}
update():更新
dict1 = {1: 'one', 3: 'three', 2: 'two', 4: 'four', 5: None}
dict2 = {5:'five'}
dict1.update(dict2)
print(dict1)
# {1: 'one', 3: 'three', 2: 'two', 4: 'four', 5: 'five'}
集合
定义
若用花括号,但是没有体现映射关系,则为集合
集合的特点:唯一,并且是无序的
a = {}
print(type(a)) #
b = {1,2,3,4,5}
print(type(b)) #
c = {1,2,3,3,4,4,5}
print(c) # {1,2,3,4,5}
#创建列表
#1.直接和前面一样{}
#2.set()函数
d = set([1,2,3,3,4,5])
print(d) # {1, 2, 3, 4, 5}
访问集合中的值
- 用for把集合中的数据一个个取出来
- 用in和not in判断数据是否在集合中
d = set([1,2,3,3,4,5])
for i in d:
print(i)
print(1 in d)
print(1 not in d)
常用函数add和remove
d = set([1,2,3,3,4,5])
d.add(6)
print(d)
d.remove(3)
print(d)
不可变集合 frozenset
number = frozenset([1,2,3,4,5])
number.add(6) # 报错