在Python中Key/Value结构的哈希表叫作Dict[字典]python
字典使用{}定义,内容是一系列的Key:Value。空的字典用{}表示函数
字符串、数字、元组均可以做为字典的key.ui
## Can build up a dict by starting with the the empty dict {} ## and storing key/value pairs into the dict like this: ## dict[key] = value-for-that-key dict = {} #建立空字典 dict['a'] = 'alpha' # 使用dict[key] = value的方式对字典赋值 dict['g'] = 'gamma' dict['o'] = 'omega' print dict ## {'a': 'alpha', 'o': 'omega', 'g': 'gamma'} print dict['a'] ## 返回 'alpha' dict['a'] = 6 ## 对 dict['a'] 赋值 'a' in dict ## True ## print dict['z'] ## 找不到对应的key,会抛出异常 if 'z' in dict: print dict['z'] ## print dict.get('z') ## None (instead of KeyError)
可使用for循环打印字典的keythis
# 方法一 for key in dict: print key ## prints a g o
可使用dict.keys() 和 dict.values()得到字典的key和valuespa
##dict.keys() ## Exactly the same as above for key in dict.keys(): print key ##打印dict.keys()返回的列表: print dict.keys() ## ['a', 'o', 'g'] ## 返回字典中value组成的列表 print dict.values() ## ['alpha', 'omega', 'gamma'] ## 能够对key进行排序,并打印对应的key和value for key in sorted(dict.keys()): print key, dict[key]
dict.item()方法能够返回由(key,value)组成的元组code
print dict.items() ## [('a', 'alpha'), ('o', 'omega'), ('g', 'gamma')] ## 循环打印key和value for k, v in dict.items(): print k, '>', v ## a > alpha o > omega g > gamma
% 操做符一样适用于字典orm
hash = {} hash['word'] = 'garfield' hash['count'] = 42 s = 'I want %(count)d copies of %(word)s' % hash # %d for int, %s for string # 'I want 42 copies of garfield'
"Del"操做符用来删除一个变量的定义。"Del"操做符可以做用于list元素或者切片blog
var = 6 del var # 删除变量var list = ['a', 'b', 'c', 'd'] del list[0] ## 删除列表中的第一个元素 del list[-2:] ## 删除列表最后两个元素 print list ## ['b'] dict = {'a':1, 'b':2, 'c':3} del dict['b'] ## 删除key=b的字典条目 print dict ## {'a':1, 'c':3}
Open()函数返回一个文件的句柄,一般用来读取或者写入一个文件排序
# Echo the contents of a file f = open('foo.txt', 'rU') for line in f: ## iterates over the lines of the file print line, ## trailing , so print does not add an end-of-line char ## since 'line' already includes the end-of line. f.close()
f.readlines()方法会将整个文件放入内存,返回以每行为元素的列表进程
f.readlines() ['Hello,时隔一个多月,终于再次回到博客啦,首先跟你们说声抱歉,许多评论没有及时回复感到很是抱歉,但愿我如今给你们的回复为时不晚。\n', '\n', '距离上次在博客上写日记过去了几个月了吧。那时的我刚刚结束大学三年级。而如今,大四上半学期已通过半啦。这半年的时间能够说忙也能够说不忙。不忙是说这半年以来的课程比较轻松,只有四门选修课,学业负担比较轻。忙是说半年以来各类错综复杂的事情,许多事情须要好好安排一下时间才能够好好把握各个“进程”的合理分配。\n', '\n', '那么就从我上第二天记开始总结一下吧。']
read()方法会读取整个文件,并把文件内容放到一个字符串中
f = open('liwei.txt') f.read() 'Hello,时隔一个多月,终于再次回到博客啦,首先跟你们说声抱歉,许多评论没有及时回复感到很是抱歉,但愿我如今给你们的回复为时不晚。\n\n距离上次在博客上写日记过去了几个月了吧。那时的我刚刚结束大学三年级。而如今,大四上半学期已通过半啦。这半年的时间能够说忙也能够说不忙。不忙是说这半年以来的课程比较轻松,只有四门选修课,学业负担比较轻。忙是说半年以来各类错综复杂的事情,许多事情须要好好安排一下时间才能够好好把握各个“进程”的合理分配。\n\n那么就从我上第二天记开始总结一下吧。'
f.write()方法能够将内容写入文件中。除此以外,在Python3中,可使用 print(string,file=f)来写入