向Python字典添加值
我正在尝试将catalog.txt文件读入字典。每行包含课程名称、学分数和1h课程集合,如下所示: CS1P,20,星期一,14,星期一,15,星期三,12,星期五,12 我正在使用的函数:向Python字典添加值,python,dictionary,Python,Dictionary,我正在尝试将catalog.txt文件读入字典。每行包含课程名称、学分数和1h课程集合,如下所示: CS1P,20,星期一,14,星期一,15,星期三,12,星期五,12 我正在使用的函数: def loadCourseCatalogue (): data = open ("catalogue.txt", "r+") print data.read () all = {} line = data.readline () while line != "":
def loadCourseCatalogue ():
data = open ("catalogue.txt", "r+")
print data.read ()
all = {}
line = data.readline ()
while line != "":
line = line.strip ().split (",")
for j in line:
all["course"] = line[0]
return all
print all
loadCourseCatalogue ()
输出应如下所示:
all = {"course": CS1P}
运行此线路后:
for j in line:
all["course"] = line[0]
就像这样:
all = {"course": CS1P, "credits": 20, "timeday": [["Monday", 14], ["Monday", 15], ["Wednesday", 12], ["Friday", 12]]}
import csv
from pprint import pprint
def pairwise(iterable):
"s -> [[s0,s1], [s2,s3], [s4, s5], ...]"
a = iter(iterable)
return [list(pair) for pair in zip(a, a)]
def loadCourseCatalogue():
all = {}
with open ("catalogue.txt", "r+") as data:
for row in csv.reader(data):
all[row[0]] = {'credits': row[1], 'timeday' : pairwise(row[2:])}
pprint(all)
return all
catalogue = loadCourseCatalogue()
在完成整个第一行之后
到目前为止,我已经尝试了各种可能的组合来添加在web上找到的值,但没有任何效果。您的第一个
打印数据。read()
会消耗文件中的所有数据,并且没有任何剩余内容,请尝试:
def loadCourseCatalogue ():
infile = open ("catalogue.txt", "r+")
data = infile.read ()
然后处理数据。您正在覆盖列表,而不是将新值附加到列表中。此外,还应该为第一次迭代提供默认的空列表。 替换:
all["course"] = line[0]
与:
还要避免使用
print data.read()
,因为它将读取所有文件,并且不会为后续的readline
留下任何内容。如果您想让它使用数据,请在打印后查找(0)
。如前所述,这将替换每行的字典键课程
,并且您的字典最后只有一行
您可以通过将all
设置为一个列表,每个值都是表示一行的dict,或者如果您的课程名称都是唯一的,则可以使用课程名称本身作为dict键,并将其值设置为该课程属性的dict。行:
print data.read ()
使用文件中的所有输入,并将文件指针定位在文件末尾。后续读取将返回一个空字符串,表示文件结束
我建议您使用for循环来迭代文件中的行。此外,由于行是逗号分隔的,因此可以使用csv
模块帮助将行拆分为单独的字段:
import csv
def loadCourseCatalogue ():
all = {}
with open("catalogue.txt") as data:
for row in csv.reader(data):
all['course'] = row[0]
# extract other fields into all
return all
但是,在处理每一行时,这将覆盖字典all
中的值。相反,您可以使用课程代码作为字典中的键,并将每个列表中的其余数据添加到其值(也是字典)。因此,针对此数据结构:
catalogue = {
'CS1P': {'credits': 20,
'timeday': [('Monday', 14),
('Monday', 15),
('Wednesday', 12),
('Friday', 12)]},
'CS2A': {'credits': 40,
'timeday': [('Monday', 10), ('Monday', 11), ('Thursday', 12)]},
#etc,
}
使用此数据结构,您可以轻松查找给定课程的数据:
>>> catalogue['CS1P']
{'credits': 20, 'timeday': [('Monday', 14), ('Monday', 15), ('Wednesday', 12), ('Friday', 12)]}
下面是一些创建这样一个字典的代码:
import csv
from pprint import pprint
def loadCourseCatalogue(data):
catalogue = {}
for row in csv.reader(data):
course = row[0]
catalogue[course] = {
'credits': int(row[1]),
'timeday': zip(row[2::2], (int(i) for i in row[3::2]))
}
return catalogue
with open('catalogue.txt') as f:
catalogue = loadCourseCatalogue(f)
pprint(catalogue)
输入:
CS1P,20,Monday,14,Monday,15,Wednesday,12,Friday,12
CS2A,40,Monday,10,Monday,11,Thursday,12
我想你想做这样的事情:
all = {"course": CS1P, "credits": 20, "timeday": [["Monday", 14], ["Monday", 15], ["Wednesday", 12], ["Friday", 12]]}
import csv
from pprint import pprint
def pairwise(iterable):
"s -> [[s0,s1], [s2,s3], [s4, s5], ...]"
a = iter(iterable)
return [list(pair) for pair in zip(a, a)]
def loadCourseCatalogue():
all = {}
with open ("catalogue.txt", "r+") as data:
for row in csv.reader(data):
all[row[0]] = {'credits': row[1], 'timeday' : pairwise(row[2:])}
pprint(all)
return all
catalogue = loadCourseCatalogue()
出于测试目的,我将数据文件示例扩展为:
CS1P,20,星期一,14,星期一,15,星期三,12,星期五,12
CS2P,19,星期一,13,星期一,14,星期三,11,星期五,11
CS3P,18,星期一,12,星期一,13,星期三,10,星期五,10
产生了以下输出:
{'CS1P':{'credits':'20',
“时间日”:星期一、十四、,
[‘星期一’、‘15’],
[‘星期三’、‘12’],
['Friday','12']],
'CS2P':{'credits':'19',
“时间日”:[[“星期一”,“13'],
[‘星期一’、‘14’],
[‘星期三’、‘11’],
['Friday','11']],
‘CS3P’:{‘学分’:‘18’,
“时间日”:[[“星期一”,“12'],
[‘星期一’、‘13’],
[‘星期三’、‘10’],
['Friday','10']]}
看起来很熟悉:)我喜欢你把时间配对的方式,不过如果你不熟悉这个把戏,可能会有点微妙。@mhawke:事实上,相同主题的一个变体…包括我基于一个类似问题的成对()。
def loadCourseCatalogue ():
all_cources={}
data = open("catalogue.txt","r").readlines()
for line in data:
_all={}
_all['credits']=line.split(',')[1]
_all['timeday']=line.split(',')[2:]
all_cources[line.split(',')[0]]=_all
return all_cources
import csv
from pprint import pprint
def pairwise(iterable):
"s -> [[s0,s1], [s2,s3], [s4, s5], ...]"
a = iter(iterable)
return [list(pair) for pair in zip(a, a)]
def loadCourseCatalogue():
all = {}
with open ("catalogue.txt", "r+") as data:
for row in csv.reader(data):
all[row[0]] = {'credits': row[1], 'timeday' : pairwise(row[2:])}
pprint(all)
return all
catalogue = loadCourseCatalogue()