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.