字典
字典是由键(key)和值(value)组成,是python唯一一个映射类型
创建字典
1.创建空字典
dict = {}
或者:dict1 = dict()
2.创建非空字典
>>> dict1 = {1:'One',2:'Two'}
>>> dict1
{1: 'One', 2: 'Two'}
3.关键字形式创建字典
>>> dict2 = dict(一 = 'one', 二 = 'two', 三 = 'three')
>>> dict2
{'一': 'one', '二': 'two', '三': 'three'}
注意:
直接给一个key值,会自动用字符串包起来,所以以下方式存在问题
>>> dict2 = dict('1' = 'one', '2' = 'two', '3' = 'three')
SyntaxError: keyword can't be an expression
或,key值设置为数字,也会报错
>>>dict2 = dict(1 = 'one', 2 = 'two', 3 = 'three')
SyntaxError: keyword can't be an expression
访问字典中的值
>>> dict1 = {1:'One',2:'Two'}
>>> dict1[1] # 通过键来访问值
'One'
- 索引字典中不存在的项报错
>>> Dict = {'name': 'Shirley', 'age': '22'}
>>> Dict['sex']
Traceback (most recent call last):
File "<pyshell#77>", line 1, in <module>
Dict['sex']
KeyError: 'sex'
将元组转化为字典
>>> dict1 = dict((('1','one'),('2','two'),('3','three')))
>>> dict1
{'1': 'one', '2': 'two', '3': 'three'}
直接给字典的键赋值
键本来存在,改写键对应的值;键不存在,创建新的键并赋值
注:序列中为不存在的位置赋值,会报错;字典中会自动创建相应的键并赋值
>>> dict1 = {1:'One',2:'Two'}
>>> dict1[3] = 'Three'
>>> dict1
{1: 'One', 2: 'Two', 3: 'Three'}
>>> dict1[1] = 'ONE'
>>> dict1
{1: 'ONE', 2: 'Two', 3: 'Three'}
清空字典
dict.clear()
del 删除字典
>>> dict1 = {1:'One',2:'Two'}
>>> del dict1[1] # 删除指定键的元素
>>> dict1
{2: 'Two'}
>>> del dict1 # 清空字典
用split()实现多个值的对应传入
>>> data = 'Shirley,22'
>>> data.split(',')
['Shirley', '22']
>>> Dict = {}
>>> Dict['name'],Dict['age'] = data.split(',')
>>> Dict
{'name': 'Shirley', 'age': '22'}
fromkeys(…)
用于创建一个新字典,以序列seq中元素做字典的键,value为字典所有键对应的初始值
语法:dict.fromkeys(seq[, value]))
参数:
seq – 字典键值列表
value – 可选参数, 设置键序列(seq)的值
返回值:返回列表
seq = ('name', 'age', 'sex')
dict = dict.fromkeys(seq)
print("New Dictionary : %s" % str(dict))
dict = dict.fromkeys(seq, 10)
print("New Dictionary : %s" % str(dict))
结果为:
New Dictionary : {‘age’: None, ‘name’: None, ‘sex’: None}
New Dictionary : {‘age’: 10, ‘name’: 10, ‘sex’: 10}
注意:
1.value传入多个参数,会被当做为一个值
dict1.fromkeys((1,2,3),('one','two','three'))
结果为:{1: (‘one’, ‘two’, ‘three’), 2: (‘one’, ‘two’, ‘three’), 3: (‘one’, ‘two’, ‘three’)}
2.不能更新列表中对应的值,会自动重新赋值
dict1.fromkeys((1,3),'数字')
结果为:{1: ‘数字’, 3: ‘数字’}
访问字典的方法
1.keys()返回字典键的引用
>>> dict1 = {}
>>> dict1 = dict1.fromkeys(range(5),'腻害了,我的哥!')
>>> dict1
{0: '腻害了,我的哥!', 1: '腻害了,我的哥!', 2: '腻害了,我的哥!', 3: '腻害了,我的哥!', 4: '腻害了,我的哥!'}
>>> for each in dict1.keys():
print(each)
0
1
2
3
4
2.values()返回字典值的引用
>>> dict1 = {}
>>> dict1 = dict1.fromkeys(range(5),'腻害了,我的哥!')
>>> dict1
{0: '腻害了,我的哥!', 1: '腻害了,我的哥!', 2: '腻害了,我的哥!', 3: '腻害了,我的哥!', 4: '腻害了,我的哥!'}
>>> for each_values in dict1.values():
print(each_values)
腻害了,我的哥!
腻害了,我的哥!
腻害了,我的哥!
腻害了,我的哥!
腻害了,我的哥!
3.items() 返回字典的每个项
for each in dict1.items():
print(each)
get()方法
返回指定键的值,如果值不在字典中返回默认值
语法:dict.get(key, default=None)
参数:
key - 字典中要查找的键
default - 如果指定键的值不存在时,返回该默认值
返回值:返回指定键的值,如果值不存在字典中返回默认值None
>>> dict1.get(7)
>>> print(dict1.get(7))
None
>>> print(dict1.get(7,'对方不想理你,并给你一巴掌~'))
对方不想理你,并给你一巴掌~
使用成员操作符,判断字典中键是否存在
>>> 4 in dict1
True
>>> 5 in dict1
False
copy() 浅拷贝
直接赋值地址相同,浅拷贝地址不同
>>> a = {1:'one',2:'two',3:'three'}
>>> b = a.copy()
>>> c = a
>>> c
{1: 'one', 2: 'two', 3: 'three'}
>>> b
{1: 'one', 2: 'two', 3: 'three'}
>>> id(a)
1306280692400
>>> id(b)
1306281261528
>>> id(c)
1306280692400
>>> c[4] = 'four' # 改变c的值
>>> a # c变化,a也变化,c由a赋值而来,指向同一块内存
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> b
{1: 'one', 2: 'two', 3: 'three'}
pop() 函数
删除指定给定键所对应的值,返回这个值并从字典中把它移除。
>>> a = {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> a.pop(2)
'two'
>>> a
{1: 'one', 3: 'three', 4: 'four'}
popitem() 函数
随机返回并删除字典中的一对键和值。
如果字典已经为空,却调用了此方法,就报出KeyError异常。
返回值:键值对(key,value)形式
>>> a
{1: 'one', 3: 'three', 4: 'four'}
>>> a.popitem()
(4, 'four')
>>> a
{1: 'one', 3: 'three'}
setdefault() 函数
此函数和get()类似, 如果键不存在于字典中,将会添加键并将值设为默认值。
语法:dict.setdefault(key, default=None)
参数:
● key – 查找的键值。
● default – 键不存在时,设置的默认键值。
返回值:如果字典中包含有给定键,则返回该键对应的值,否则返回为该键设置的值。
>>> a = {1: 'one', 3: 'three'}
>>> print(a.setdefault('小白'))
None
>>> a
{1: 'one', 3: 'three', '小白': None}
>>> a = {1: 'one', 3: 'three'}
>>> print(a.setdefault(5,'five'))
five
update() 函数
把字典dict2的键/值对更新到dict里。
语法:dict.update(dict2)
参数:
dict2 – 添加到指定字典dict里的字典。
返回值:
没有任何返回值。
>>> a = {1: 'one', 3: 'three'}
>>> b = {1:'ONE'}
>>> a.update(b)
>>> a
{1: 'ONE', 3: 'three', 5: 'five'}