字典写入文件用法总结

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字典写入文件用法总结相关的知识,希望对你有一定的参考价值。


技术分享










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/







































































以上是关于字典写入文件用法总结的主要内容,如果未能解决你的问题,请参考以下文章

python写入csv文件的几种方法总结

将字典写入文件

将字典写入文件[重复]

将字典写入文本文件?

将列表字典写入 CSV 文件

将字典写入文本文件