字典
映射类型 不是序列类型
标志:{}
由键和值共同组成
fromkeys
创建新的字典,无法用它修改一个原有字典
>>> dict1={}
>>> dict1.fromkeys((1,2,3))
{1: None, 2: None, 3: None}
>>> dict1.fromkeys((1,2,3),'Number')
{1: 'Number', 2: 'Number', 3: 'Number'}
#不会将one two three依次赋值给1,2,3
>>> dict1.fromkeys((1,2,3),('one','two','three'))
{1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}
#不能批量修改1和3的值,而会创建新的字典
>>> dict1.fromkeys((1,3),'数字')
{1: '数字', 3: '数字'}
常用BIF方法
dict1.clear() 清空字典
pop 给定键,弹出对应的值
popitem 给定键,弹出一个项 随机弹 无法指定
setdefult
update
>>> a
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> a.pop(2)
'two'
>>> a
{1: 'one', 3: 'three', 4: 'four'}
>>> a.popitem()
(4, 'four')
>>> a
{1: 'one', 3: 'three'}
>>> a.setdefault('小白')
>>> a
{1: 'one', 3: 'three', '小白': None}
>>> a.setdefault(5,'five')
'five'
>>> a
{1: 'one', 3: 'three', '小白': None, 5: 'five'}
>>> b={'小白':'狗'}
>>> a.update(b)
>>> a
{1: 'one', 3: 'three', '小白': '狗', 5: 'five'}
浅拷贝和赋值
>>> a={1:'one',2:'two',3:'three'}
>>> b=a.copy() #浅拷贝
>>> c=a #直接赋值
>>> c
{1: 'one', 2: 'two', 3: 'three'}
>>> a
{1: 'one', 2: 'two', 3: 'three'}
>>> b
{1: 'one', 2: 'two', 3: 'three'}
>>> id(a)
2639651321960
>>> id(b)
2639651069128
>>> id(c)
2639651321960
>>> c[4]='four'
>>> c
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> a
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> b
{1: 'one', 2: 'two', 3: 'three'}
补充
键(key)必须是可哈希的对象,不能是可变类型(变量、列表、字典本身等)
值(value)没有限制
集合
-
集合的唯一作用:确保里面包含的元素的唯一性,集合内不可能存在两个相同的元素
-
集合是无序的不支持索引
-
创建集合的方法:1.把一堆元素用花括号括起来
2.直接使用set()工厂函数 -
存储方式:哈希存储(跟字典一样)
哈希函数计算,相同的元素得到的哈希值(存放地址)是相同的,所以集合中所有相同的元素都会覆盖掉; 哈希函数计算的地址不可能是按顺序排放的,所以集合强调是无序的
>>> num={}
>>> type(num)
<class 'dict'>
>>> num2={1,2,3,4,5}
>>> type(num2)
<class 'set'>
#自动清除重复
>>> num2={1,2,3,3,4,5,5,4}
>>> num2
{1, 2, 3, 4, 5}
#创建集合
>>> set1=set([1,2,3,4,5,5])
>>> set1
{1, 2, 3, 4, 5}
#使用集合清除列表中的重复元素
>>> num1=[1,2,3,4,5,4,3,2]
>>> num1=list(set(num1))
>>> num1
[1, 2, 3, 4, 5]
常用方法
>>> num2
{1, 2, 3, 4, 5}
>>> 1 in num2
True
>>> '1' in num2
False
>>> num2.add(6)
>>> num2
{1, 2, 3, 4, 5, 6}
>>> num2.remove(5)
>>> num2
{1, 2, 3, 4, 6}
frozenset:不可变集合 不能被更改或删除