码迷,mamicode.com
首页 > 其他好文 > 详细

字典写入文件用法总结

时间:2017-05-05 19:24:40      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:int   otto   技术   eve   rate   ref   tty   lis   googl   


技术分享










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/













字典写入文件用法总结

标签:int   otto   技术   eve   rate   ref   tty   lis   googl   

原文地址:http://www.cnblogs.com/xinping-study/p/6814543.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!