小甲鱼Python课程笔记第25讲,第26讲 —— 字典

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没有改变。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值