Python入门——Day6(字典,前拷贝,pop与popitem)

0.目录

字典——当索引不好用时
创建与访问字典
字典的内建方法
前拷贝
pop 与 popitem

1.Python字典

字典(Dictionary)在Python中,字典是一系列的 键——值 对,每个键都与一个值相关联,可以使用键来访问与之相关的值。这个值可以是数字,字符串,列表,乃至字典。

键,值:就好比我们查字典时,单词即为 键(key)单词的含义就是值(value)

字典又可以叫哈希表,映射,散列或是关系数组。

每个键与值用冒号隔开(:),每对用逗号分隔,整体放在花括号中({})。

键必须独一无二,但值则不必。
映射图解

2.创建与访问字典

>>> brand = ['李宁','耐克','小甲鱼']
>>> slogan = ['一切皆有可能','Just do it','编程改变世界']
>>> print('小甲鱼的口号是:',slogan[brand.index('小甲鱼')])
小甲鱼的口号是: 编程改变世界
>>> dict = {'李宁':'一切皆有可能','耐克':'just do it','小甲鱼':'编程改别世界'}
>>> print('小甲鱼:',dict['小甲鱼'])
小甲鱼: 编程改别世界

>>> dict2 = {1:'one',2:'two',3:'three'}
>>> dict2
{1: 'one', 2: 'two', 3: 'three'}
>>> dict2[2]
'two'

3.字典的内建方法


fromkeys(...)
	dict.fromkeys(S,[,v])->Nem dict with keys from S and values equal to v
	v defaults to None
>>> dict1 = {}
>>> dict1.fromkeys((1,2,3))
{1: None, 2: None, 3: None}#没赋值默认None
>>> dict1.fromkeys((1,2,3),'number')
{1: 'number', 2: 'number', 3: 'number'}
>>> dict1.fromkeys((1,2,3),('one','two','three'))#不是一一对应赋值
{1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}
>>> dict1.fromkeys((1,3),'数字')
{1: '数字', 3: '数字'}#不是指定修改对应键的值


>>> dict1 = dict1.fromkeys(range(5),'赞')
>>> dict1
{0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞'}
>>> for eachKey in dict1.keys():
	print(eachKey)

#打印对应的所有的键	
0
1
2
3
4
>>> for eachValue in dict1.values():
	print(eachValue)

#打印所以值	
赞
赞
赞
赞
赞
>>> for eachItem in dict1.items():
	print(eachItem)

#打印所有项	
(0, '赞')
(1, '赞')
(2, '赞')
(3, '赞')
(4, '赞')

>>> print(dict1[4])>>> print(dict1[5])
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    print(dict1[5])
KeyError: 5

>>> dict1.get(5)
>>> print(dict1.get(5))
None
>>> dict1.get(5,'没有的!')
'没有的!'
>>> 4 in dict1
True
>>> 5 in dict1
False
>>> dict1
{0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞'}
>>> dict1.clear()
>>> dict1
{}

4.前拷贝与赋值

>>> a = {1:'one',2:'two',3:'three'}
>>> b = a.copy()
>>> c = a
>>> b
{1: 'one', 2: 'two', 3: 'three'}
>>> c
{1: 'one', 2: 'two', 3: 'three'}
>>> a
{1: 'one', 2: 'two', 3: 'three'}
>>> id(a)
1980623851264
>>> id(c)
1980623851264
>>> id(b)#前拷贝的位置与赋值不同
1980624279552
例如在a中添加元素four,c随之改变,b就不受影响
>>> c[4] = 'four'
>>> a
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> c
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> b
{1: 'one', 2: 'two', 3: 'three'}

5.pop与popitem

>>> 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.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'}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值