1、创建和使用字典
>>>phonebook = {'Alice':'2341','Beth':'9102','Cecil':'3258'}
2、dict函数
#利用(键,值)对序列建立字典
>>>items = [('name','Gumby'),('age','42')]
>>>d=dict(items)
>>>d
{'age':'42','name':'Gumby'}
>>>d['name']
'Gumby'
#通过关键字参数创建字典
>>>d=dict(name='Gumby',age=42)
>>>d
{'age':'42','name':'Gumby'}
3、字典的格式化字符串
>>>phonebook
{'Beth':'9102','Alice':'2341','Cecil':'3258'}
>>>"Cecil's phone number is %(Cecil)s." % phonebook
"Cecil's phone number is 3258"
4、字典方法
#clear
>>>d={}
>>>d['name']='Gumby'
>>>d['age']=42
>>>d
{'age':42,'name':'Gumby'}
>>>returned_value=d.clear()
>>>d
{}
>>>returned_value
None
#copy(浅复制)
>>>y = x.copy()
#deepcopy
>>>from copy import deepcopy
>>>d={}
>>>d['name']=['Alfred','Bertrand']
>>>c=d.copy()
>>>dc=d.deepcopy()
>>>d['name'].append('Clive')
>>>c
{'name':['Alfred','Bertrand','Clive']}
>>>dc
{'name':['Alfred','Bertrand']}
#fromkeys(使用给定的键建立新的字典)
>>>{}.fromkeys(['name','age'])
{'age':None,'name':Node}
>>>dict.fromkeys(['name','age'],'(unknown)')
{'age':'(unknown)','name':'(unknown)'}
#get(访问字典项,若不存在没有异常,得到None值)
>>>d={}
>>>d.get('name')
None
#items(将字典所有项以列表方式返回)
>>>d={'age':42,'name':'Gumby'}
>>>d.items()
[('age',42),('name','Gumby')]
#iteritems(返回一个迭代器对象而不是列表)
#pop
>>>d={'x':1,'y':2}
>>>d.pop(x)
1
>>>d
{'y':2}
#setdefault(类似get方法,能获得给定键的相关联的值,还能在字典中不含有给定键的情况下设置相应的键值)
>>>d={}
>>>d.setdefault('name','N?A')
'N?A'
>>>d
{'name':'N?A'}
>>>d['name']='Cumby'
>>>d.setfault('name','N?A')
'Gumby'
>>>d
{'name':'Gumby'}
#updata(利用一个字典项更新另一个字典)
>>>d={'name':'Gumby','age':42}
>>>x={'sex':'female'}
>>>d.update(x)
>>>d
{'name':'Gumby','age':42,'sex':'female'}
#values(以列表的形式返回字典中的值)
>>>d={}
>>>d[1]=1
>>>d[2]=2
>>>d[3]=3
>>>d.values()
[1,2,3]