基本语法:
dict = {'ob1':'computer', 'ob2':'mouse', 'ob3':'printer'}
技巧:
字典中包含列表:dict={'yangrong':['23','IT'],"xiaohei":['22','dota']}
字典中包含字典:dict={'yangrong':{"age":"23","job":"IT"},"xiaohei":{"'age':'22','job':'dota'"}}
可用命令:
root@yangrong:~# cd /Python
root@yangrong:/python# python
Python 2.7.5+ (default, Sep 19 2013,13:48:49)
[GCC 4.8.1] on linux2
Type "help","copyright", "credits" or "license" for moreinformation.
>>> import tab
>>> d={}
>>> d.
d.__class__( d.__ge__( d.__len__( d.__setitem__( d.has_key( d.setdefault(
d.__cmp__( d.__getattribute__( d.__lt__( d.__sizeof__( d.items( d.update(
d.__contains__( d.__getitem__( d.__ne__( d.__str__( d.iteritems( d.values(
d.__delattr__( d.__gt__( d.__new__( d.__subclasshook__( d.iterkeys( d.viewitems(
d.__delitem__( d.__hash__ d.__reduce__( d.clear( d.itervalues( d.viewkeys(
d.__doc__ d.__init__( d.__reduce_ex__( d.copy( d.keys( d.viewvalues(
d.__eq__( d.__iter__( d.__repr__( d.fromkeys( d.pop(
d.__format__( d.__le__( d.__setattr__( d.get( d.popitem(
>>> d.
增加字典元素
>>> nameinfo={}
>>> nameinfo['a1']='yangrong' #若字典里有a1主键,则覆盖原来的值,没有,则添加
>>> nameinfo
{'a1': 'yangrong'}
遍历字典主键与键值
>>> for k, value innameinfo.items():
... print k,value
...
a1 yangrong
查看字典所有主键
>>> dict = {'ob1':'computer','ob2':'mouse', 'ob3':'printer'}
>>>
>>>
>>> dict.keys()
['ob2', 'ob3', 'ob1']
判断字典中是否有该主键
>>> dict.keys()
['ob2', 'ob3', 'ob1']
>>> dict.has_key('ob2') #或'ob2' in dict
True
>>> dict.has_key('ob4')
False
也有人用循环方法来判断
for key in dict.keys():
但是这种方法毕竟不够简洁,
查看字典所有键值内容
>>> dict = {'ob1':'computer','ob2':'mouse', 'ob3':'printer'}
>>> dict.values()
['mouse', 'printer', 'computer']
列出所有项目
>>> dict.items()
[('ob2', 'mouse'), ('ob3', 'printer'),('ob1', 'computer')]
清空字典
>>> dict.clear()
>>> dict
{}
拷贝字典
>>> dict
{'ob2': 'mouse', 'ob3': 'printer', 'ob1':'computer'}
>>> a=dict
>>> a
{'ob2': 'mouse', 'ob3': 'printer', 'ob1':'computer'}
>>> b=dict.copy()
>>> b
{'ob2': 'mouse', 'ob3': 'printer', 'ob1': 'computer'}
比较字典
>>> cmp(a,b)
首先比较主键长度,然后比较键大小,然后比较键值大小,(第一个大返回1,小返回-1,一样返回0)
更新字典
>>>dict={'yangrong':{"age":"23","job":"IT"},"xiaohei":{"'age':'22','job':'dota'"}}
>>> dict
{'xiaohei':set(["'age':'22','job':'dota'"]), 'yangrong': {'age': '23', 'job':'IT'}}
>>> dict['xiaohei']=111 #修改一级字典
>>> dict
{'xiaohei': 111, 'yangrong': {'age': '23','job': 'IT'}}
>>> dict['yangrong']['age']=25 #修改二级字典
>>> dict
{'xiaohei': 111, 'yangrong': {'age': 25,'job': 'IT'}}
>>> dict={'yangrong':['23','IT'],"xiaohei":['22','dota']}
>>>dict['xiaohei'][1]="dota2" #修改字典中列表某项,1是代表列表中第2个字符串。
>>> dict
{'xiaohei': ['22', 'dota2'], 'yangrong':['23', 'IT']}