>字典结构
>>键值对(融合了PHP中的特点)
>>创建字典,使用成对的花括号{ },使用冒号表示键值对
例如:my_dict = {'John':879798,'Bob':8757,'mike':725466}
其他方法:dict(zip([1,2,3],[4,5,6]))或dict([(1,4),(2,5),(3,6)])
>>访问字典:使用方括号[ ] ,使用键作为索引
例如:print my_dict print my_dict['tom']
>>字典运算符和方法
len(my_dict)字典中键值对的数量
key in my_dict快速判断key是否为字典中的键(=>my_dict.has_key(key))
for key in my_dict:能够遍历数组中所有的键(不是值)
my_dict.items()全部的键值对,以列表的形式存在(好像Python中称数组为列表吧)
my_dict.keys() 全部的键
my_dict.values()全部的值
my_dict.clear() 清空字典
>>关于文件处理中涉及到的一些函数
# reading the essay and count the top ten using words
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()
>>定义:无需不重复元素的集合,和字典相同没有值,只有键
>>创建集合:x = set() x = {key1,key2,...}
>>添加和删除:x.add('body') x.remove('body')
>>集合的运算符
-差集
&交集
|并集
!=不等于判断
==判断相等
in成员运算
for枚举运算