字典(dict)是由 ’ { } ’ 括起来的一组元素,其包含的元素是以键值对的形式存在的,其中 key 在字典是唯一的,value可以不唯一。
1、字典的创建
字典的创建方法有很多种,以及空字典的创建方式。
>>> d1 = {'one':1,'two':2,'three':3}
>>> d1
{'one': 1, 'two': 2, 'three': 3}
>>> d2 = dict(one=1,two=2,three=3)
>>> d2
{'one': 1, 'two': 2, 'three': 3}
>>> d3 = dict(zip(['one','two','three'],[1,2,3]))
>>> d3
{'one': 1, 'two': 2, 'three': 3}
>>> d4 = dict({'one':1,'two':2,'three':3})
>>> d4
{'one': 1, 'two': 2, 'three': 3}
>>> d1 == d2 == d3 == d4
True
>>> d5 = dict([('one',1),('two',2),('three',3)])
>>> d5
{'one': 1, 'two': 2, 'three': 3}
>>> d6 = dict((('one',1),('two',2),('three',3)))
>>> d6
{'one': 1, 'two': 2, 'three': 3}
>>> d7 = {}
>>> d8 = dict()
>>> d7 == d8
True
2、增删查改
(1)字典中添加元素
dict[key] = value,若出现同名的可以,则新的 value 覆盖原有的 value。
>>> d = {}
>>> d['one'] = 1
>>> d
{'one': 1}
>>> d['one'] = 2
>>> d
{'one': 2}
(2)查找元素
dict[key] : 根据 key 值获取 value 值;
dict.items() : 遍历字典,将字典转换成列表的形式保存;
dict.keys() : 遍历字典,获取字典中的 key 值,保存到列表中;
dict.values() : 遍历字典,获取字典中的 value 值,保存到列表中;
get(key) : 获取 key 所对应的 value 值,若没有,则返回 None ;
get(key,default) : 获取 key 所对应的 value 值,若没有,则返回 default ;
>>> d = dict(one=1,two=2,three=3,four=4)
>>> d
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> d['one']
1
>>> for i in d:
print(i)
one
two
three
four
>>> for i in d.items():
print(i)
('one', 1)
('two', 2)
('three', 3)
('four', 4)
>>> for i in d.keys():
print(i)
one
two
three
four
>>> for i in d.values():
print(i)
1
2
3
4
(3)删除元素
del d[key] : 删除键为 key 的键值对;
pop(key,[,default]) : 弹出 key 的键值对,返回 value 的值;
popitem() : 从字典末尾删除键值对;
clear() : 清空字典;
>>> d = dict(one=1,two=2,three=3,four=4,five=5)
>>> d
{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
>>> del d['three']
>>> d
{'one': 1, 'two': 2, 'four': 4, 'five': 5}
>>> d.pop('two')
2
>>> d.popitem()
('five', 5)
>>> d
{'one': 1, 'four': 4}
>>> d.clear()
>>> d
{}
(4)修改元素
dict1.update(dict2) : 类似于字典合并,相同的键值对会被 dict2 覆盖,dict1中没有的会添加;
fromkeys(seq[,default]) : 相当于新建列表,将 seq 转成字典,若未指定 value,则为None;
>>> d1 = dict(one=1,two=2)
>>> d2 = dict(three=3,four=4)
>>> d1.update(d2)
>>> d1
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> lst = ['aa','bb','cc']
>>> d = dict.fromkeys(lst,00)
>>> d
{'aa': 0, 'bb': 0, 'cc': 0}