[英]Read a text file and form a dictionary in python
I have file data.txt , below python code reads a text and forms dictionary. 我有data.txt文件,在python代码下面读取文本并形成字典。
file: data.txt 档案: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 类似地,如何以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 . 或者python中是否有任何方法可以形成数据库,从而可以轻松获取数据。
try the following approach: 尝试以下方法:
>>> data = """10/20 Name vinay phone +91094xxx
... 05/31 Name hunachyal phone +91jndjxx
... 11/23 Name mine phone +92jdddxxx
... """
>>>
>>> result = {}
>>>
>>> for line in data.splitlines():
... dataList = line.split()
... result[dataList[0]] = {dataList[1]: dataList[2], dataList[3]: dataList[4]}
...
>>> result
{'11/23': {'Name': 'mine', 'phone': '+92jdddxxx'}, '10/20': {'Name': 'vinay', 'phone': '+91094xxx'}, '05/31': {'Name': 'hunachyal', 'phone': '+91jndjxx'}}
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, 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. 如果您使用的是
infile = open(...)
而不是with open() as infile:
来处理文件句柄,则应记住之后要close
文件句柄。
Try this:) 尝试这个:)
infile = open("data.txt")
for line in infile:
List_array = [w.strip() for w in line.split("\t")]
bday_list[List_array[0]] ={"Phone":List_array[1],"Name":List_array[2]}
This should work for you: 这应该为您工作:
f = open('filename.txt').readlines()
f = [i.strip('\n').split() for i in f]
new_dict = {i[0]:{i[b]:i[b+1] for b in range(1, len(i), 2) if b+1 < len(i)} for i in f}
print new_dict
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.