字典——当索引不好用时
创建与访问字典
字典的内建方法
前拷贝
pop 与 popitem
字典(Dictionary)在Python中,字典是一系列的 键——值 对,每个键都与一个值相关联,可以使用键来访问与之相关的值。这个值可以是数字,字符串,列表,乃至字典。
键,值:就好比我们查字典时,单词即为 键(key)单词的含义就是值(value)
字典又可以叫哈希表,映射,散列或是关系数组。
每个键与值用冒号隔开(:),每对用逗号分隔,整体放在花括号中({})。
>>> 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'
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 "" , 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
{}
>>> 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'}
>>> 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'}