首页 > 代码库 > 字典写入文件用法总结

字典写入文件用法总结


技术分享










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/













字典写入文件用法总结