@nalan90
2017-07-28T21:08:16.000000Z
字数 2881
阅读 519
Python高效编程技巧实战
常用函数
创建字典
In [1]: d = {'name':'zhangshuang','age':27,'sex':'male'}
In [2]: d
Out[2]: {'age': 27, 'name': 'zhangshuang', 'sex': 'male'}
In [3]: d = dict((['name','zhangshuang'],['age',27]))
In [4]: d
Out[4]: {'age': 27, 'name': 'zhangshuang'}
In [5]: d = dict.fromkeys(['a','b','c'],100)
In [6]: d
Out[6]: {'a': 100, 'b': 100, 'c': 100}
访问字典里的值
In [7]: d = {'name':'zhangshuang','age':27,'sex':'male'}
In [11]: d.get('name')
Out[11]: 'zhangshuang'
## 使用get函数,当key不存在时,返回None
In [12]: d.get('abc')
In [13]: d['name']
Out[13]: 'zhangshuang'
## 直接访问,当key不存在,抛错
In [14]: d['abc']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-14-e51fd128be60> in <module>()
----> 1 d['abc']
KeyError: 'abc'
## has_key可判断dict里是否存在一个某个key
In [15]: if d.has_key('abc'):
....: print d['abc']
....: else:
....: print 'key not exists'
....:
key not exists
删除字典元素
In [21]: d = {'age': 27, 'name': 'zhangshuang', 'sex': 'male'}
In [22]: d
Out[22]: {'age': 27, 'name': 'zhangshuang', 'sex': 'male'}
In [23]: del d['age']
In [24]: d.pop('sex')
Out[24]: 'male'
In [25]: d
Out[25]: {'name': 'zhangshuang'}
In [26]: d.clear()
In [27]: d
Out[27]: {}
In [29]: d.popitem()
Out[29]: ('age', 27)
In [30]: d
Out[30]: {'name': 'zhangshuang', 'sex': 'male'}
In [31]: d.popitem()
Out[31]: ('name', 'zhangshuang')
其他操作
In [33]: d = {'age': 27, 'name': 'zhangshuang', 'sex': 'male'}
## 以list形式返回所有key
In [34]: d.keys()
Out[34]: ['age', 'name', 'sex']
## 以list形式返回所有value
In [35]: d.values()
Out[35]: [27, 'zhangshuang', 'male']
## 以list返回dict所有key-value
In [36]: d.items()
Out[36]: [('age', 27), ('name', 'zhangshuang'), ('sex', 'male')]
## dict遍历key value
In [39]: for k,v in d.iteritems():
....: print k, v
....:
age 27
name zhangshuang
sex male
## dict遍历key
In [40]: for k in d.iterkeys():
....: print k
....:
age
name
sex
## dict遍历value
In [41]: for v in d.itervalues():
....: print v
....:
27
zhangshuang
male
In [43]: d
Out[43]: {'age': 27, 'name': 'zhangshuang', 'sex': 'male'}
In [44]: d1 = {'age':30,'school':'MIT'}
## dict更新操作
In [45]: d.update(d1)
In [46]: d
Out[46]: {'age': 30, 'name': 'zhangshuang', 'school': 'MIT', 'sex': 'male'}
In [47]: dict.setdefault?
Docstring: D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
Type: method_descriptor
In [48]: d
Out[48]: {'age': 30, 'name': 'zhangshuang', 'school': 'MIT', 'sex': 'male'}
In [49]: d.setdefault('age',34)
Out[49]: 30
In [50]: d
Out[50]: {'age': 30, 'name': 'zhangshuang', 'school': 'MIT', 'sex': 'male'}
In [51]: d.setdefault('salary',25000.00)
Out[51]: 25000.0
In [52]: d
Out[52]:
{'age': 30,
'name': 'zhangshuang',
'salary': 25000.0,
'school': 'MIT',
'sex': 'male'}