-
语法
get()方法语法:
dict.get(key, default=None)
-
参数
- key -- 字典中要查找的键。
- default -- 如果指定键的值不存在时,返回该默认值值。
-
返回值
返回指定键的值,如果值不在字典中返回默认值None。
-
实例
以下实例展示了 get()函数的使用方法:
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 27} print "Value : %s" % dict.get('Age') print "Value : %s" % dict.get('Sex', "Never")
以上实例输出结果为:
Value : 27
Value : Never
-
access log例子
#!/usr/bin/pyhton f = open('access.log') res = {} print f for line in f: #print line ip = line.split(' ')[0] #print ip #print ip.split(' ') res[ip] = res.get(ip,0)+1 print res f.close()
-
-
排序对log
-
#!/usr/bin/pyhton f = open('access.log') res = {} #print f for line in f: #print line ip = line.split(' ')[0] #print ip #print ip.split(' ') res[ip] = res.get(ip,0)+1 f.close() #print res.items()i res_list = res.items() for j in range(10): for i in range(len(res_list)-1): if res_list[i][1] > res_list[i+1][1]: res_list[i],res_list[i+1] = res_list[i+1],res_list[i] i = 0 html_str = '<table border="1px">' for r in res_list[:-10:-1]: i = i+1 html_str += '<tr><td>No%s </td> <td>%s</td><td> %s </td></tr>' %(i,r[0],r[1]) html_str +='</table>' html_f = open('res.html','w') html_f.write(html_str) #print res html_f.close()
-
-
结果
-
-
-
No1 192.168.50.104 6558 No2 192.168.50.106 3700 No3 192.168.50.19 123 No4 192.168.50.105 74 No5 192.168.50.109 13 No6 192.168.50.62 9 No7 192.168.50.183 6 No8 192.168.50.54 4 No9 192.168.50.56 4
-
-
根据两个指标来排序
-
#!/usr/bin/pyhton f = open('access.log') res = {} #print f for line in f: #print line tmp = line.split(' ') ip,url = tmp[0],tmp[6] #print ip #print ip.split(' ') res[(ip,url)] = res.get((ip,url),0)+1 for key in res: print key,'----',res[key] f.close()