字典
1. “键-值”对的可变序列,
2. ‘键’ 可以是任意不可变序列,如整数、实数、复数、字符串、元组等,不允许重复,‘值’ 可以重复
3. 可以使用globals() 和 locals() 查看当前作用域内所有全局/局部变量和值的字典
1 #创建字典
2 >>keys = [‘a‘,‘b‘,‘c‘]
3 >>values = [1,2,3]
4 >>adic = dict(zip(keys,values))
5 >>print(adict)
6 {‘a‘: 1, ‘b‘: 2, ‘c‘: 3}
7
8 >>person = dict(name=‘Jack‘,age=37)
9 >>print(person)
10 {‘name‘: ‘Jack‘, ‘age‘: 37}
11
12 # 删除字典或其元素
13 >>del person[‘age‘]
14 >>print(person)
15 {‘name‘: ‘Jack‘}
16 >>person.pop(‘name‘)
17 ‘Jack‘
18 >>print(person)
19 {}
20
21 # 使用clear() 清空字典
22 >>person = dict(name=‘Jack‘,age=37)
23 >>print(person)
24 {‘name‘: ‘Jack‘, ‘age‘: 37}
25 >>person.clear()
26 >>print(person)
27 {}
1 # 读取字典元素
2 >>adict = dict(name=‘Nik‘,age=32,sex=‘man‘,work=False)
3 >>adict[‘name‘]
4 ‘Nik‘
5 >>adict.get(‘age‘)
6 32
7
8 # 返回键值对
9 >>adict.items()
10 dict_items([(‘name‘, ‘Nik‘), (‘age‘, 32), (‘sex‘, ‘man‘), (‘work‘, False)])
11
12 # 返回值
13 >>adict.values()
14 dict_values([‘Nik‘, 32, ‘man‘, False])
15
16 # 返回键
17 >>adict.keys()
18 dict_keys([‘name‘, ‘age‘, ‘sex‘, ‘work‘])
1 # 添加与修改元素
2 >>perc = dict(name=‘Nik‘,age=32,sex=‘man‘,work=False)
3 >>perc[‘address‘] = ‘wht‘
4 >>print(aditc)
5 {‘address‘: ‘wht‘, ‘age‘: 32, ‘name‘: ‘Nik‘, ‘sex‘: ‘man‘, ‘work‘: False}
6
7 # 使用update将另一个字典的键值对全部添加到当前字典中,从头部添加
8 >>perc.update({‘id‘:256,‘height‘:175})
9 >>print(perc)
10 {‘address‘: ‘wht‘, ‘age‘: 32, ‘height‘: 175, ‘id‘: 256, ‘name‘: ‘Nik‘,
11 ‘sex‘: ‘man‘, ‘work‘: False}
12
13 # 生成1000个随机字符,并统计每个字符出现次数
14 >>import string
15 >>import random
16 >>x=string.ascii_letters+string.digits+string.punctuation
17 >>print(x)
18 ‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!"#$%&\‘()*+,-./:;<=>[email protected][\\]^_`{|}~‘
19 >>y=[random.choice(x) for i in range(1000)]
20 >>z = ‘‘.join(y)
21 >>d = dict()
22 >>for ch in z:
23 d[ch] = d.get(ch,0)+1
24 >>print(d)
25 #结果较多,不列出
26
27 #使用collections模块的Counter类统计字符次数
28 >>import colllections import Counter
29 >>freq = Counter(z)
30 >>freq.items()
31 # 出现次数最多的
32 >>freq.most_common(1)
33 [(‘A‘, 18)]
34 # 最多次数前3
35 >>freq.most_common(3)
36 [(‘A‘, 18), (‘)‘, 18), (‘:‘, 17)]