python读取文件中的内容为字典,读取文本文件并在python中形成字典

I have file data.txt , below python code reads a text and forms dictionary.

file: data.txt

10/20 vinay

05/31 hunachyal

11/23 mine

bday_list = {}

infile = open("data.txt")

for line in infile:

List_array = [w.strip() for w in line.split("\t")]

bday_list[List_array[0]] = List_array[1]

# print line

print bday_list

Op: {'11/23': 'mine', '10/20': 'vinay', '05/31': 'hunachyal'}

Similarly how to get dictinaory for the below file in the format as shown in OP

file

10/20 Name vinay phone +91094xxx

05/31 Name hunachyal phone +91jndjxx

11/23 Name mine phone +92jdddxxx

OP:

{'11/23': {'Phone': '+91kexxx', 'Name': 'mine'}, '10/20': {'Phone': '+919xxxx', 'Name': 'vinay'}, '05/31': {'Phone': '+9194xxxx', 'Name': 'hunachyal'}}

Or Is there any method in python to form data base where i can easily fetch data .

解决方案

You can also try this

bday_list = {}

with open('data.txt', 'r') as R:

for line in R:

l = line.strip().split() # split the line to list

bday_list[l[0]] = {k:v for k,v in zip(l[1::2], l[2::2])}

PS,

If you are using infile = open(...) and not with open() as infile: to work with a file handle, you should remember to close the file handle afterward.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值