0x01 clear
clear方法清除字典中所有的项。这是一个原地操作,无返回值
1 >>> d = {} 2 >>> d[‘name‘] = ‘Gumby‘ 3 >>> d[‘age‘] = 13 4 >>> d 5 {‘age‘: 13, ‘name‘: ‘Gumby‘} 6 >>> value = d.clear 7 >>> print value 8 <built-in method clear of dict object at 0x7f8f905c37f8>
0x02 get
get(key[, default])
get方法是一个更宽松的访问字典项的方法。一般来说,如果试图访问字典中不存在的项时会出错,而用get就不会,当访问的项不存在时,还可以自定义默认值
1 >>> d = {} 2 >>> d[‘name‘] 3 Traceback (most recent call last): 4 File "<stdin>", line 1, in <module> 5 KeyError: ‘name‘ 6 >>> print d.get(‘name‘) 7 None 8 >>> print d.get(‘name‘, ‘default_value‘) 9 default_value
get方法也可以用来做一些统计之类的,比如统计每个字符有多少个
1 #!/usr/bin/env python 2 # coding=utf-8 3 4 str = ‘‘‘ 5 aaaaaaaaaaaaaa 6 bbbbbbbbbbbbb 7 cccccccccccccccc 8 dddddddddddddd 9 33333333333 10 44444444444 11 `````````````` 12 ‘‘‘ 13 14 counts = {} 15 16 for c in str: 17 counts[c] = counts.get(c, 0) + 1 18 19 print counts 20 21 """ 22 {‘a‘: 14, ‘`‘: 14, ‘c‘: 16, ‘b‘: 13, ‘d‘: 14, ‘\n‘: 8, ‘3‘: 11, ‘4‘: 11} 23 """
时间: 2024-09-30 19:59:51