dict1={}
dict2=dict1.fromkeys((1,2,3))
dict3=dict1.fromkeys((1,2,3),'number')
dict4=dict1.fromkeys((1,2,3),('one','two','three'))
dict5=dict1.fromkeys(range(32),'赞')
print(dict2)
print(dict3)
print(dict4)
print(dict5)
打印结果
{1: None, 2: None, 3: None}
{1: 'number', 2: 'number', 3: 'number'}
{1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}
{0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞', 5: '赞', 6: '赞', 7: '赞', 8: '赞', 9: '赞', 10: '赞', 11: '赞', 12: '赞', 13: '赞', 14: '赞', 15: '赞', 16: '赞', 17: '赞', 18: '赞', 19: '赞', 20: '赞', 21: '赞', 22: '赞', 23: '赞', 24: '赞', 25: '赞', 26: '赞', 27: '赞', 28: '赞', 29: '赞', 30: '赞', 31: '赞'}
for eachkey in dict5.keys():
print(eachkey)
输出为
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
for eachvalue in dict5.values():
print(eachvalue)
输出为
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
for eachitem in dict5.items():
print(eachitem)
输出为
(0, '赞')
(1, '赞')
(2, '赞')
(3, '赞')
(4, '赞')
(5, '赞')
(6, '赞')
(7, '赞')
(8, '赞')
(9, '赞')
(10, '赞')
(11, '赞')
(12, '赞')
(13, '赞')
(14, '赞')
(15, '赞')
(16, '赞')
(17, '赞')
(18, '赞')
(19, '赞')
(20, '赞')
(21, '赞')
(22, '赞')
(23, '赞')
(24, '赞')
(25, '赞')
(26, '赞')
(27, '赞')
(28, '赞')
(29, '赞')
(30, '赞')
(31, '赞')
在字典中用in not in 检查元素是否在字典中
print(31 in dict5)
print(32 in dict5)
返回值为
True
False
清空一个字典 clear()
dict6=dict5.clear()
print(dict6)
返回值
None
注意!
若定义
a={'姓名':'哈哈哈'}
b=a
然后令
a={}
此时,打印出来,
a={}
b={'姓名':'哈哈哈'}
若,
a={'姓名':'哈哈哈'}
b=a
令
a.clear()
打印
{}
{}
copy 函数
a={1:'one',2:'two',3:'three'}
b=a.copy()
c=a
打印a,b,c都是
{1: 'one', 2: 'two', 3: 'three'}
但是他们并不是同一个地址其中a,c是一个地址,b是一个地址。
如果对c加一个数值
c[4]='four'
a和c都变为
{1: 'one', 2: 'two', 3: 'three',4:'four'}
{1: 'one', 2: 'two', 3: 'three',4:'four'}
b没有改变。