id,name,phone,car1,小明,1001,大众2,小马,1002,宝骏3,小乐,1003,北汽4,小李,1004,哈弗
# 低级版本lst = []with open('2019-05-07',mode='r',encoding='utf-8') as f: s = f.readline() for line in f: dic = {} # 每行一个字典 ls = line.strip().split(',') dic['id'] = ls[0] dic['name'] = ls[1] dic['phone'] = ls[2] dic['car'] = ls[3] lst.append(dic)print(lst)
# 高级版本lst = []with open('2019-05-07',mode='r',encoding='utf-8') as f: first_name = f.readline().strip().split(',') for line in f: dic = {} ls = line.strip().split(',') for i in range(len(first_name)): dic[first_name[i]] = ls[i] lst.append(dic)print(lst)
2.
name:小李 age:18 salary:10000 car:宝马name:小花 age:19 salary:12000 car:奔驰
f = open('a1',mode='r',encoding='utf-8')lst = []for line in f: dic ={} ll = line.split() for e in ll: ls = e.split(':') dic[ls[0]] = ls[1] lst.append(dic)print(lst)
结果
[{ 'name': '小李', 'age': '18', 'salary': '10000', 'car': '宝马'}, { 'name': '小花', 'age': '19', 'salary': '12000', 'car': '奔驰'}]