python保存字典和读取字典的实例代码

yipeiwu_com6年前Python基础

读取一个已经保存了的字典

f = open('dict_th','r')
a = f.read()
dict_hi = eval(a)
f.close()

保存一个字典

dict = {}
list1 = []
list2 = []
for line in lines:
  line = line.strip()
  if ">" in line:
    list1.append(line)
  else:
    list2.append(line)
for i in range():
  dict[list1[i]] = list2[i]
f6 = open("dict_th",'w')
f6.write(str(dict))
f6.close()

ps:下面看下python 使用列表和字典存储信息

"""
  作者:白
  时间:2018年1月9日
  需求:假设你很多汽车,通过不断询问您是否要将车辆添加到您的库存中,
  如果您这样做,那么它将会询问汽车的细节。如果没有,应用程序将打印所有汽车的详细信息并退出。
  功能:循环添加汽车相关信息,并记录信息到字典中
"""
def main():
  car_list = []
  while True:
   add_inventory = input('是否添加汽车信息?(y/n):')
   if add_inventory == 'y':
    car_model = input('请输入汽车的型号:')
    car_color = input('请输入汽车的颜色:')
    car_year = input('请输入汽车的年限:')
    car_miles = input('请输入汽车的公里:')
    car_dict={'model':car_model,'color':car_color,'year':car_year,'miles':car_miles}
    print(car_dict)
    car_list.append(car_dict)
   elif add_inventory == 'n':
    print(car_list)
    break
if __name__ == '__main__':
  main()

总结

以上所述是小编给大家介绍的python保存字典和读取字典的实例代码,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

相关文章

Python按行读取文件的简单实现方法

1:readline() file = open("sample.txt") while 1: line = file.readline() if not line:...

为Python的Tornado框架配置使用Jinja2模板引擎的方法

tornado 默认有一个模板引擎但是功能简单(其实我能用到的都差不多)使用起来颇为麻烦, 而jinja2语法与django模板相似所以决定使用他. 下载jinja2 还是用pip 下载...

详解opencv中画圆circle函数和椭圆ellipse函数

详解opencv中画圆circle函数和椭圆ellipse函数

1.      void ellipse(InputOutputArray img, Point center, Size axes,...

详解Python利用random生成一个列表内的随机数

首先,需要导入random模块: import random 随机取1-33之间的1个随机数,可能重复: random.choice(range(1,34)) print得到...

基于Django contrib Comments 评论模块(详解)

老版本的Django中自带一个评论框架。但是从1.6版本后,该框架独立出去了,也就是本文的评论插件。 这个插件可给models附加评论,因此常被用于为博客文章、图片、书籍章节或其它任何东...