字典
第四章:字典
1、字典是python中唯一内建的映射类型,存储在一个特定的键(key)里,键里可以是数字、字符串甚至是元组
#字典是由多个键及与其对应的值构成的对组成。
#创建字典
#(1)直接创建
>>> phonebook = {'Alice': '2341','Beth': '9102','Cecil': '3258'}
#(2)dic函数创建
>>> items = [('name','Gumby'),('age',42)]
>>> d=dict(items)
>>> d
{'age': 42, 'name': 'Gumby'}
>>> d['name']
'Gumby'
#(3)dict函数也可通过关键参数来创建字典
>>> d=dict(name='Gumby',age=42)
>>> d
{'age': 42, 'name': 'Gumby'}
>>> dict() #空字典
{}
2、字典基本操作
>>> a=len(d) #长度
>>> a
2
>>> d['age'] #d[k]返回关联到键k上的值
42
>>> d['no']='123'
>>> d
{'age': 42, 'name': 'Gumby', 'no': '123'}
>>> del d['no'] #del d[k] 删除键为k的项
>>> d
{'age': 42, 'name': 'Gumby'}
>>> 'age' in d # k in d检查d中是否含有键为k的项
True
>>> x = [] #空列表
>>> x[42] = 'Fooobar' #将值关联到一个并不存在的索引,报错,需要[None] * 43, x[42]='Foobar'才可
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
x[42] = 'Fooobar'
IndexError: list assignment index out of range
>>> x={} #空字典
>>> x[42]='Foobar' #可以直接自动添加关联
>>> x
{42: 'Foobar'}
>>>
字典示例
# 简单数据库
# 使用人民作为键的字典。每个人用另一个字典表示,其键'phone'和'addr'分别表示他们的电话号码和地址。
people = {
'Alice' : {
'phone' : '2341',
'addr' : 'Foo drive 23'
},
'Beth' : {
'phone' : '9102',
'addr' : 'Bar street 42'
},
'Cecil' : {
'phone' : '3158',
'addr' : 'Bar avenue 90'
}
}
# 针对电话号码和地址使用的描述性标签,会在打印输出的时候使用到
labels = {
'phone' : 'phone number',
'addr' : 'address'
}
name = input('Name: ')
# 查找电话号码还是地址?使用正确的的键
request = input("phone number (p) or address (a)? ")
#使用正确的键:
if request == 'p' : key = 'phone'
if request == 'a' : key = 'addr'
# 如果名字是字典中的有效键才打印信息:
if name in people: print("%s's %s is %s." %(name,labels[key],people[name][key]))
#输出
Name: Beth
phone number (p) or address (a)? a
Beth's address is Bar street 42.
>>>
3、字典的格式化字符串
>>> phonebook = {'Beth': '9102','Alice': '2341','Cecil': '3258'}
>>> "Cecil's phone number is %(Cecil)s." %phonebook #使用字典格式化的方法
"Cecil's phone number is 3258."
#使用模板的例子
>>> template = '''<html>
<head><title>%(title)s</title></head>
<body>
<h1>%(title)s</h1>
<p>%(text)s</p>
</body>'''
>>> data ={'title': 'My Home Page', 'text': 'Welcome to my home page!'}
>>> print(template %data)
<html>
<head><title>My Home Page</title></head>
<body>
<h1>My Home Page</h1>
<p>Welcome to my home page!</p>
</body>
>>>
4、字典方法
#clear方法清除字典中的所有项,无返回值或者返回None
>>> d={}
>>> d['name']='Gumby'
>>> d['age']=42
>>> d
{'age': 42, 'name': 'Gumby'}
>>> returned_value = d.clear()
>>> d
{}
>>> print(returned_value)
None
#例1不使用clear方法
>>> x={}
>>> y=x #x,y指向同一字典
>>> x['key']='value'
>>> y
{'key': 'value'}
>>> x={} #x指向另一新的字典,而原字典不变,y仍指向原来的字典
>>> y
{'key': 'value'}
>>>
#例2使用clear方法清除,清除了原字典
>>> x={}
>>> y=x
>>> x['key']='value'
>>> y
{'key': 'value'}
>>> x.clear() #使用clear()清空了原始字典
>>> y
{}
#copy方法返回一个具有相同键--值对的新字典
#浅复制方法(shallow copy)在副本中替换值时原始字典不受影响,但修改原始字典受影响
>>> x={'username': 'admin','machines': ['foo','bar','baz']}
>>> y=x.copy()
>>> y
{'username': 'admin', 'machines': ['foo', 'bar', 'baz']}
>>> y['username']='wsf' #替换
>>> y
{'username': 'wsf', 'machines': ['foo', 'bar', 'baz']}
>>> y['machines'].remove('foo') #修改,移除'foo'
>>> y
{'username': 'wsf', 'machines': ['bar', 'baz']} #副本值替换,修改
>>> x
{'username': 'admin', 'machines': ['bar', 'baz']} #原始字典只修改,不替换
>>>
#深复制(deep copy),复制其包含所有的值,可以使用那个copy模块的deepcopy函数
>>> from copy import deepcopy
>>> d={}
>>> d['names']=['Alfred','Bertrand'] #原始字典
>>> c=d.copy() #浅复制
>>> dc=deepcopy(d) #深复制
>>> c
{'names': ['Alfred', 'Bertrand']}
>>> d['names'].append('Clive') #对原始字典修改
>>> c
{'names': ['Alfred', 'Bertrand', 'Clive']} #浅复制修改了
>>> dc
{'names': ['Alfred', 'Bertrand']} #深复制未被修改
#fromkeys()方法
#说明:fromkeys()方法使用给定的键建立新的字典,每个键默认对应的值为None
>>> {}.fromkeys(['name','age']) #构造一个空字典
{'age': None, 'name': None}
>>> dict.fromkeys(['name','age']) #直接在所有字典的类型dict上面调用方法
{'age': None, 'name': None}
>>> dict.fromkeys(['name','age'],'(unkown)') #不使用None作为默认值,自己提供默认值
{'age': '(unkown)', 'name': '(unkown)'}
# get()方法:更宽松的访问字典项的方法
>>> d={}
>>> print(d['name']) #访问字典中不存在的项会出错
Traceback (most recent call last):
File "<pyshell#85>", line 1, in <module>
print(d['name'])
KeyError: 'name'
>>> print(d.get('name')) #用get()访问不会报错
None
>>> d.get('name','N/A') #自定义默认值,替换None
'N/A'
>>> d['name']='Eric' #键存在,get像普通的字典查询一样
>>> d.get('name')
'Eric'
字典get()方法完整示例
#说明: 使用get()的简单数据库
people = {
'Alice':{
'phone': '2341',
'addr': 'Foo drive 23'
},
'Beth':{
'phone': '9102',
'addr': 'Bar street 42'
},
'Cecil':{
'phone': '3158',
'addr': 'Baz avenue 90'
}
}
labels = {
'phone': 'phone number',
'addr': 'address'
}
name=input('Name: ')
#查找电话号码还是地址?
request = input('phone number(p) or address(a)? ')
#使用正确的键
key = request #如果请求即不是'p'也不是'a'
if request == 'p' : key ='phone'
if request == 'a' : key = 'addr'
#使用get()提供默认值:
person = people.get(name, {}) #若输入的name不存在,则用空字典表示该person
label = labels.get(key, key) #若用户输入的不是p或a,则将输入内容作为label
result = person.get(key, 'not available') #若key(即用户输入不存在),则输出notavailable
print("%s's %s is %s. " %(name,label,result))
#运行结果
Name: Alice
phone number(p) or address(a)? a
Alice's address is Foo drive 23.
Name: Alice
phone number(p) or address(a)? d
Alice's d is not available.
# has_key()方法
#说明:has_key方法可以检查字典中是否含有给出的键,python3.0中不包括这个函数,可以用 k in dict 的方式代替;
# items()和iteritems()方法
#说明:items方法将所有的字典项以列表方式返回,这些列表项中的每一项都来自于(键,值),返回时没有特殊的顺序
>>> d={'title': 'python web site', 'url': 'http://www.python.org', 'spam': 0}
>>> d.items()
dict_items([('url', 'http://www.python.org'), ('spam', 0), ('title', 'python web site')])
>>>
#iteritems()将字典以迭代器形式返回,Python3中不再支持
>>> phonebook = {'Alice': '2341', 'Beth': '9102', 'Ceil': '0123'}
>>> it = phonebook.iteritems()
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
it = phonebook.iteritems()
AttributeError: 'dict' object has no attribute 'iteritems'
#pop()方法
#说明:pop()根据键获得值并弹出,并从字典中删除键-值
>>> d={'x': 1,'y' : 2}
>>> d.pop('x')
1
>>> d
{'y': 2}
#popitem()方法
#说明:popitem()方法弹出随机的项
>>> d= {'Alice': '2341', 'Beth': '9102', 'Ceil': '0123'}
>>> d.popitem()
('Beth', '9102')
>>> d
{'Alice': '2341', 'Ceil': '0123'}
#setdefault()方法
#说明:setdefault()方法,获得与给定键相关联的值,若无键则返回默认值None,默认值可重设
>>> d ={}
>>> d.setdefault('name','N/A') #不存在该键,返回默认值None
'N/A'
>>> d
{'name': 'N/A'}
>>> d['name']='boss'
>>> d.setdefault('name','N/A')
'boss'
>>> d
{'name': 'boss'}
#update()方法
#说明:update()如键不存在则添加,相同的键则覆盖
>>> d= {'Alice': '2341', 'Beth': '9102', 'Ceil': '0123'}
>>> x={'Jack' : '0738'}
>>> d.update(x)
>>> d
{'Jack': '0738', 'Beth': '9102', 'Alice': '2341', 'Ceil': '0123'}
#values()
#说明:values方法以列表的形式返回字典中的值
>>> d={}
>>> d[1]=1
>>> d[2]=2
>>> d[3]=3
>>> d[4]=1
>>> d.values()
dict_values([1, 2, 3, 1])