1.创建字典
http://skyfen.iteye.com/blog/567571 Python字典的应用详解
方法①: >>> dict1 = {} >>> dict2 = {'name': 'earth', 'port': 80} >>> dict1, dict2 ({}, {'port': 80, 'name': 'earth'}) 方法②:从Python 2.2 版本起 >>> fdict = dict((['x', 1], ['y', 2])) >>> fdict {'y': 2, 'x': 1}
2. 字典排序
http://www.kunli.info/2009/05/07/sorting-dictionaries-by-value-in-python/ Python中最快的字典排序方法
after sort the return is a list of tuple
def sort2(d,r=True):#从大到小 sort by value return sorted(d.iteritems(), key=lambda x: x[1] , reverse=r)
def sort2(d,r=False):#从小到大 sort by key return sorted(d.iteritems(), key=lambda x: x[0] , reverse=r)
sortDic=sort2(dic,True)
3. 字典遍历
http://5iqiong.blog.51cto.com/2999926/806230 遍历python字典几种方法
脚本:
执行结果:
4. 查找元素has_key
dic={} for i in words: if dic.has_key(i) is False: dic[i]=1 else: dic[i]+=1
5. 统计
while True >0: if dic.has_key(ky) is False: dic[ky]=1 else: dic[ky]+=1