note 11 字典

时间:2023-03-08 22:25:53

字典 Dictionary

+什么是字典?

+一系列的"键-值(key-value)"对

+通过"键"查找对应的"值"

+类似纸质字典,通过单词索引表找到其相应的定义

C++:map

Java:HashTable or HashMap

例如:电话本

note 11 字典

创建字典

使用 { } 创建字典
使用 : 指明 键:值 对
my_dict = {'John':86411234,'Bob':86419453,'Mike':86412387} 键必须是 不可变 的且不重复,值可以是 任意 类型

访问字典

使用 [ ] 运算符,键作为索引
print my_dict['Bob']
print my_dict['Tom']#WRONG! 增加一个新的对
my——dict['Tom'] = 86417649

字典中键是无序的

字典运算符和方法

len(my_dict)

求字典中键-值对的数量

key in my_dict

快速判断key是否为字典中的键:O(1)
等价于my_dict.has_key(key) 时间复杂度为常数,不随字典规模变化

for key in my_dict:

枚举字典中的键,注:键是无序的

更多方法

my_dict.items()- 返回全部的键-值对 以列表形式
my_dict.keys()- 全部的键
my_dict.values()- 全部的值
my_dict.clear()- 清空字典

+字母计数

读取一个字符串,计算每个字母出现的个数

1.生成26个变量,代表每个字母出现的个数

2.生成具有26个元素的列表,将每个字母转化为相应的索引值,如a->0,b->1,...

s = 'asffghjljkl'

lst = [0] * 26

for i in s:
lst[ord(i) - 97] += 1 print lst

3.生成一个字典,字母做键,对应出现的次数做值

s = 'asffghjljkl'

d = {}

for i in s:
if i in d:
d[i] += 1
else :
d[i] = 1 print d

+单词计数

读取小说“emma.txt”,打印前10个最常见单词

是否还能直观的将每个单词转化为相应的数字?

sort默认升序

f = open('emma.txt')

word_freq = {}

for line in f:
words = line.strip().split()
for word in words:
if word in word_freq:
word_freq[word] += 1
else:
word_freq[word] = 1 freq_word = []
for word,freq in word_freq.items():
freq_word.append((freq,word)) freq_word.sort(reverse = True) for freq,word in freq_word[:10]:
print word f.close()

+翻转字典

生成一个新字典,其键为原字典的值,值为原字典的键

同一个值,可能对应多个键,需要用列表存储

d1 = {'Zhang':123,'Wang':456,'Li':123,'Zhao':456}
d2 = {} for name,room in d1.items():
if room in d2:
d2[room].append(name)
else:
d2[room] = [name] print d2