
https://developers.google.com/edu/python/sorting
利用字典來描述數據, 例如: 有log數據, IP地址數據,可以用ip作為key,
dict = {}
dict['a'] = 'alpha'
dict['g'] = 'gamma'
dict['o'] = 'omega'
dict['a'] = 6
對字典的遍歷默認是對key的遍歷
for key in dict: print key <==> for key in dict.keys(): print key
列舉字典所有的鍵
dict.keys()
列舉排過序的key 和值
for key in sorted(dict.keys()):
print key, dict[key]
列舉鍵值對.items 生成二元組形式
dict.items() ## [('a', 'alpha'), ('o', 'omega'), ('g', 'gamma')]
獲取每個鍵和值
for k, v in dict.items():
print k, '>', v
列舉字典所有的值
## Get the .values() list:
dict.values() ##
File:
The special mode 'rU' is the "Universal" option for text files where it's smart about converting different line-endings so they always come through as a simple '\n'.
# 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()
Files Unicode
The "codecs" module provides support for reading a unicode file.
import codecs
f = codecs.open('foo.txt', 'rU', 'utf-8')
for line in f:
# here line is a *unicode* string
For writing, use f.write() since print does not fully support unicode.
http://www.saltycrane.com/blog/2008/01/saving-python-dict-to-file-using-pickle/
