字典里的键可以是数字、字符串、元组
4.1 字典的使用
>>> name=[‘Alice‘,‘Beth‘,‘Earl‘]
>>> numbers=[‘2341‘,‘9102‘,‘0142‘] #电话号码必须使用字符串,二不能是整数,因为电话号码可能以0开头
>>> numbers[name.index(‘Beth‘)]
‘9102‘
4.2 创建和使用字典
>>> data ={‘title‘:‘My Home Page‘,‘text‘:‘Welcome to my home page!‘}
4.2.1 dict 函数
通过其他映射,或者键值序列建立字典
>>> items=[(‘name‘,‘Gumby‘),(‘age‘,42)]
>>> d=dict(items)
>>> d
{‘age‘: 42, ‘name‘: ‘Gumby‘}
>>> d[‘name‘]
‘Gumby‘
直接用dict来创建字典,用键值对、或者映射和关键字参数来创建字典
>>> d = dict(name=‘Gumby‘,age=42)
>>> d
{‘age‘: 42, ‘name‘: ‘Gumby‘}
dict函数和tuple、str函数类似
>>> c=dict()
>>> c
{}
4.2.2 基本字典操作
len(d) 返回d中键值对的数量
d[k]
d[k]=v
del d[k]
k in d 检查d中是否含有k的项
>>> d
{‘age‘: 42, ‘name‘: ‘Gumby‘}
>>> len(d)
2
>>> d[‘age‘]
42
>>> d[‘age‘]=35
>>> d
{‘age‘: 35, ‘name‘: ‘Gumby‘}
>>> ‘age‘ in d
True
>>> ‘age1‘ in d
False
>>> del d[‘age‘]
>>> d
{‘name‘: ‘Gumby‘}
字典和列表的比较
1、键类型 最常用的是字符串和元组
2、自动添加 列表赋值必须初始化列表
3、成员资格,字典查找的是键,列表查找的是值
4.2.3 字典的格式化字符串
>>> phonebook={‘Beth‘:‘9102‘,‘Alice‘:‘2341‘,‘Cecil‘:‘3258‘}
>>> "Cecil‘s phone number is %(Cecil)s." % phonebook
"Cecil‘s phone number is 3258."
>>> data ={‘title‘:‘My Home Page‘,‘text‘:‘Welcome to my home page!‘}
>>> template=‘‘‘<html>
... <head><title>%(title)s</title></head>
... <body>
... <h1>%(title)s</h1>
... <p>%(text)s</p>
... </body>‘‘‘
>>> 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.2.4 字典方法
1、clear 返回None
>>> d[‘name‘]=‘Gumby‘
>>> d.clear()
>>> d
{}
应用一:
>>> x = {}
>>> y = x
>>> x[‘key‘]=‘value‘
>>> y
{‘key‘: ‘value‘}
>>> x
{‘key‘: ‘value‘}
>>> x={}
>>> y
{‘key‘: ‘value‘}
>>>
应用二
>>> x = {}
>>> y = x
>>> x[‘key‘]=‘value‘
>>> x
{‘key‘: ‘value‘}
>>> y
{‘key‘: ‘value‘}
>>> x.clear()
>>> x
{}
>>> y
{}
2、copy 浅复制,修改引用类型的key,对原来的字典有影响
>>> x={‘username‘:‘admin‘,‘machines‘:[‘foo‘,‘bar‘,‘baz‘]}
>>> y=x.copy()
>>> y[‘username‘]
‘admin‘
>>> x[‘username‘]
‘admin‘
>>> y[‘username‘]=‘mlh‘
>>> y[‘machines‘].remove(‘bar‘)
>>> y
{‘username‘: ‘mlh‘, ‘machines‘: [‘foo‘, ‘baz‘]}
>>> x
{‘username‘: ‘admin‘, ‘machines‘: [‘foo‘, ‘baz‘]}
deepcopy 深度拷贝
>>> from copy import deepcopy
>>> d={}
>>> d[‘names‘]=[‘Alfred‘,‘Bertrand‘]
>>> c=d.copy()
>>> dc=deepcopy(d)
>>> d[‘names‘].append(‘Clive‘)
>>> c
{‘names‘: [‘Alfred‘, ‘Bertrand‘, ‘Clive‘]}
>>> d
{‘names‘: [‘Alfred‘, ‘Bertrand‘, ‘Clive‘]}
>>> dc
{‘names‘: [‘Alfred‘, ‘Bertrand‘]}
3、fromkeys 用给定key创建新的字典
>>> {}.fromkeys([‘name‘,‘age‘])
{‘age‘: None, ‘name‘: None}
>>> dict.fromkeys([‘name‘,‘age‘])
{‘age‘: None, ‘name‘: None}
>>> dict.fromkeys([‘name‘,‘age‘],‘(unkown)‘)
{‘age‘: ‘(unkown)‘, ‘name‘: ‘(unkown)‘}
4、get,访问不到不会报错
>>> d={}
>>> print d[‘name‘]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: ‘name‘
>>> print d.get(‘name‘)
None
>>> print d.get(‘name‘,‘N/A‘)
N/A
>>> d[‘name‘]=‘Eric‘
>>> print d.get(‘name‘,‘N/A‘)
Eric
5、has_key 等价于 k in d
>>> d={}
>>> d.has_key(‘name‘)
False
>>> d[‘name‘]=‘Eric‘
>>> d.has_key(‘name‘)
True
6、items和iteritems 将字典以列表形式返回
>>> d={‘title‘:‘Python web site‘,‘url‘:‘http://www.python.org‘,‘spam‘:‘0‘}
>>> d.items()
[(‘url‘, ‘http://www.python.org‘), (‘spam‘, ‘0‘), (‘title‘, ‘Python web site‘)]
>>> d
{‘url‘: ‘http://www.python.org‘, ‘spam‘: ‘0‘, ‘title‘: ‘Python web site‘}
>>> it=d.iteritems()
>>> it
<dictionary-itemiterator object at 0x7fe272022af8>
>>> list(it) #将迭代器转换为list
[(‘url‘, ‘http://www.python.org‘), (‘spam‘, ‘0‘), (‘title‘, ‘Python web site‘)]
7、keys和iterkeys
>>> d
{‘url‘: ‘http://www.python.org‘, ‘spam‘: ‘0‘, ‘title‘: ‘Python web site‘}
>>> d.keys()
[‘url‘, ‘spam‘, ‘title‘]
>>> ks=d.iterkeys()
>>> ks
<dictionary-keyiterator object at 0x7fe272022c00>
>>> list(ks)
[‘url‘, ‘spam‘, ‘title‘]
8、pop 获取对应key的值,并从原字典中删除
>>> d={‘x‘:1,‘y‘:2}
>>> d.pop(‘x‘)
1
>>> d
{‘y‘: 2}
9、popitem 随机弹出一组key和value
>>> d={‘title‘:‘Python web site‘,‘url‘:‘http://www.python.org‘,‘spam‘:‘0‘}
>>> d.popitem()
(‘url‘, ‘http://www.python.org‘)
>>> d
{‘spam‘: ‘0‘, ‘title‘: ‘Python web site‘}
>>> d.popitem()
(‘spam‘, ‘0‘)
>>> d
{‘title‘: ‘Python web site‘}
>>> d.popitem()
(‘title‘, ‘Python web site‘)
>>> d
{}
10、setdefault
>>> d={}
>>> d.setdefault(‘name‘,‘N/A‘) #不指定默认值,默认使用None
‘N/A‘
>>> d
{‘name‘: ‘N/A‘}
>>> d[‘name‘]=‘Gumby‘
>>> d.setdefault(‘name‘,‘N/A‘)
‘Gumby‘
>>> d
{‘name‘: ‘Gumby‘}
11、update 用一个字典更新另外一个字典,相同的key会覆盖
>>> d={‘title‘:‘python Web site‘,‘url‘:‘http://www.python.org‘}
>>> x={‘title‘:‘Python Language Website‘}
>>> d.update(x)
>>> d
{‘url‘: ‘http://www.python.org‘, ‘title‘: ‘Python Language Website‘}
12 values和itervalues
>>> d={}
>>> d[1]=1
>>> d[2]=3
>>> d[3]=2
>>> d[4]=1
>>> d.values()
[1, 3, 2, 1]
>>> it=d.itervalues()
>>> it
<dictionary-valueiterator object at 0x7fe272022c58>
>>> list(it)
[1, 3, 2, 1]