Python基础入门学习笔记 026 字典:当索引不好用时2

发布时间 2023-08-23 10:01:12作者: 一杯清酒邀明月

fromkey()方法用于创建并返回一个新的字典。它有两个参数,第一个参数是字典的键;第二个参数是可选的,是传入键的值。如果不提供,默认是None

1 >>> dict1 = {}
2 >>> dict1.fromkeys((1,2,3))
3 {1: None, 2: None, 3: None}
4 >>> dict2 = {}
5 >>> dict2.fromkeys((1,2,3),"Number")
6 {1: 'Number', 2: 'Number', 3: 'Number'}
7 >>> dict3 = {}
8 >>> dict3.fromkeys((1,2,3),('one','two','three'))
9 {1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}

访问字典的方法有key()、values()和items()

key()用于返回字典中的键,value()用于返回字典中所有的值,item()当然就是返回字典中所有的键值对(也就是项)

1 >>> dict1 = dict1.fromkeys(range(5),'')
2 >>> dict1.keys()
3 dict_keys([0, 1, 2, 3, 4])
4 >>> dict1.values()
5 dict_values(['', '', '', '', ''])
6 >>> dict1.items()
7 dict_items([(0, ''), (1, ''), (2, ''), (3, ''), (4, '')])

get()方法提供了更宽松的方式去访问字典项,当键不存在的时候,get()方法并不会报错,只是默默第返回一个None,表示啥都没找到:

1 >>> dict1.get(10)
2 >>> dict1.get(4)
''

如果希望找不到数据时返回指定的值,可以在第二个参数设置对应的默认返回值:

>>> dict1.get(32,'木有')
'木有'

如果不知道一个键是否在字典中,可以使用成员资格操作符(in 或 not in)来判断

1 >>> 31 in dict1
2 False
3 >>> 4 in dict1

clear()可清空一个字典

1 >>> dict1
2 {0: '', 1: '', 2: '', 3: '', 4: ''}
3 >>> dict1.clear()
4 >>> dict1
5 {}

copy()方法是复制字典(全拷贝)

 1 >>> a = {1:'one',2:'two',3:'three'}
 2 >>> b = a.copy()
 3 >>> id(a)
 4 52448840
 5 >>> id(b)
 6 52503624
 7 >>> a[1] = 'four'
 8 >>> a
 9 {1: 'four', 2: 'two', 3: 'three'}
10 >>> b
11 {1: 'one', 2: 'two', 3: 'three'}

pop()是给定键弹出对应的值,popitem()是随机弹出一个项

1 >>> a.pop(2)
2 'two'
3 >>> a
4 {1: 'four', 3: 'three'}
5 >>> a.popitem()
6 (1, 'four')
7 >>> a
8 {3: 'three'}

setdefault()方法与get()方法相似,但setdefault()在字典中找不到相应的键值时会自动添加

 1 >>> a = {1:'one',2:'two',3:'three'}
 2 >>> a.setdefault(2)
 3 'two'
 4 >>> a.setdefault(4)
 5 >>> a
 6 {1: 'one', 2: 'two', 3: 'three', 4: None}
 7 
 8 update()方法可以更新字典
 9 
10 >>> a = {1:'one','小白':None}
11 
12 >>> b = {'小白':''}
13 >>> a.update(b)
14 >>> a
15 {1: 'one', '小白': ''}