【发布时间】:2017-12-04 06:11:43
【问题描述】:
我想从 python 中的文本文件创建字典。我的文本文件是:
John Doe
Apples
Bananas
Oranges
Jane Dear
Apples
Bananas
Peaches
文本文件的格式为:
Name
Fruit
Fruit
.....
Fruit
empty line
Name
Fruit
.....
我想返回一个以水果为键、名称为值的字典,例如:
{"Apples":["John Doe", "Jane Dear"], "Bananas":["John Doe", "Jane Dear"], "Peaches":["Jane Dear"], "Oranges":["John Doe"]}
我只是不完全确定如何格式化文本文件。提前致谢!
编辑:到目前为止我做了什么
def common(text):
x = open(text, "r")
a = {}
b = []
line = x.readline()
while line != "":
b.append(line)
line = courses.readline()
return b
def create_dict(lst):
a = []
b = {}
names = []
fruits = []
while lst != []:
if " " in lst[1]:
names += lst[1]
else:
fruits += lst[1]
这就是我有点迷路的地方......
【问题讨论】:
-
请展示您迄今为止的尝试。
标签: python list file dictionary text