Python字典的setdefault()方法

setdefault(key[, default])

If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.

如果键在字典中,返回这个键所对应的值。如果键不在字典中,向字典 中插入这个键,并且以default为这个键的值,并返回 default。default的默认值为None

 

 
   
  1. >>> dict={} 
  2. >>> dict['key']='a' 
  3. >>> dict 
  4. {'key''a'
  5. >>> dict.setdefault('key''b')  # 键key存在,故返回简直a. 
  6. 'a' 
  7. >>> dict 
  8. {'key''a'
  9. >>> dict.setdefault('key0''b'# 键key0不存在,故插入此键,并以b为键值. 
  10. 'b' 
  11. >>> dict 
  12. {'key0''b''key''a'


日志分析

利用字典分析apache访问日志的脚本,以提取IP地址,字节数和状态

 

 
   
  1. #!/usr/bin/env python 
  2. """ 
  3. USAGE: 
  4. apache_log.py some_log_file 
  5.  
  6. This script takes one command line argument:the name of a log file to parse.It then parses the lof file and generates a report which associates remote hosts with number of bytes transferred to them. 
  7. """ 
  8.  
  9. import sys 
  10.  
  11. def dictify_logline(line): 
  12.         split_line = line.split() 
  13.         return {'remote_host': split_line[0],'status':split_line[8],'bytes_sent':split_line[9]} 
  14.  
  15. def generate_log_report(logfile): 
  16.         report_dict = {} 
  17.         for line in logfile: 
  18.                 line_dict = dictify_logline(line) 
  19.                 print line_dict 
  20.                 try
  21.                         bytes_sent = int(line_dict['bytes_sent']) 
  22.                 except ValueError: 
  23.                         continue 
  24.                 report_dict.setdefault(line_dict['remote_host'],[]).append(bytes_sent) 
  25.         return report_dict 
  26.  
  27. if __name__ == "__main__"
  28.         if not len(sys.argv) > 1
  29.                 print __doc__ 
  30.                 sys.exit(1
  31.         infile_name = sys.argv[1
  32.         try
  33.                 infile = open(infile_name,'r'
  34.         except ValueError: 
  35.                 print "You must specify a valid file to parse" 
  36.                 sys.exit(1
  37.         log_report = generate_log_report(infile) 
  38.         print log_report 
  39.         infile.close()