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)
http://1.guotie.sinaapp.com/?p=19 对python的字典(dict)按键/值(key, value)排序
sortDic=sort2(dic,True)
3. 字典遍历
http://5iqiong.blog.51cto.com/2999926/806230 遍历python字典几种方法
脚本:
- #!/usr/bin/python
- dict={"a":"apple","b":"banana","o":"orange"}
- print "##########dict######################"
- for i in dict:
- print "dict[%s]=" % i,dict[i]
- print "###########items#####################"
- for k,v in dict.items():
- print "dict[%s]=" % k,v
- print "###########iteritems#################"
- for k,v in dict.iteritems():
- print "dict[%s]=" % k,v
- print "###########iterkeys,itervalues#######"
- for k,v in zip(dict.iterkeys(),dict.itervalues()):
- print "dict[%s]=" % k,v
执行结果:
- ##########dict######################
- dict[a]= apple
- dict[b]= banana
- dict[o]= orange
- ###########items#####################
- dict[a]= apple
- dict[b]= banana
- dict[o]= orange
- ###########iteritems#################
- dict[a]= apple
- dict[b]= banana
- dict[o]= orange
- ###########iterkeys,itervalues#######
- dict[a]= apple
- dict[b]= banana
- dict[o]= orange
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