文件操作脚本(一)

把这个写到一个字典里
苹果 6888
茶杯 25
娃娃 998
伟哥 99

goods_dic = {}
goods_list = []
f = open('练习','r')
for line in f:
    goods_dic ={"name":None,'price':None}  #建立一个空字典
    line = line.strip()
    goods_lst = line.split()
    goods_dic['name'] = goods_lst[0]     #给字典赋值
    goods_dic['price'] = goods_lst[1]
    goods_list.append(goods_dic)   #添加到列表中
print(goods_list)
f.close()

结果
[{'name': '鑻规灉', 'price': '6888'}, {'name': '鑼舵澂', 'price': '25'}, {'name': '濞冨▋', 'price': '998'}, {'name': '浼熷摜', 'price': '99'}]

打印到一个列表中

dict1 = {}
f = open('练习','r')
for line in f:
    line = line.strip()
    goods_lst = line.split()
    dict1[goods_lst[0]] = goods_lst[1]
print(dict1)

{'鑻规灉': '6888', '鑼舵澂': '25', '濞冨▋': '998', '浼熷摜': '99'}

 

posted @ 2017-12-11 19:11  明王不动心  阅读(137)  评论(0编辑  收藏  举报