如何从python中的文件将项分配给字典?
所以我是一个初学者程序员,正在学习编程:在cousera上制作优质代码课程。我有一个文件如何从python中的文件将项分配给字典?,python,python-2.7,Python,Python 2.7,所以我是一个初学者程序员,正在学习编程:在cousera上制作优质代码课程。我有一个文件restaurant\u small.txt restaurant.txt格式为餐厅至评级 georgieporgie:50 dumpling r us:70 queens cafe:60 我能一行一行地读 dictionary = {} our_file = open(file) #using an iterator to read files for line in iter(our_file):
restaurant\u small.txt
restaurant.txt格式为餐厅至评级
georgieporgie:50
dumpling r us:70
queens cafe:60
我能一行一行地读
dictionary = {}
our_file = open(file)
#using an iterator to read files
for line in iter(our_file):
dictionary = ??
我想能够建立一个字典{'restaurant':'rating'}
我该怎么做呢?一步一步的简单步骤是值得赞赏的
dictionary = {}
with open('restaurant_small.txt') as our_file:
for line in our_file:
rest, rating = line.split(':')
dictionary[rest] = int(rating)
建议使用正确处理异常等情况的文件,并确保文件始终在结束时关闭。这大致相当于
our_file = open('restaurant_small.txt')
# do the rest
our_file.close()
除非在close()
之前发生错误,否则仍将调用它。与with
语句更接近的等价物是
our_file = open('restaurant_small.txt')
try:
# do the rest
finally:
our_file.close()
与Lev的答案相似,但构建一个线条生成器,首先从末尾拆分,然后使用dict理解一次性构建它
with open('input') as fin:
lines = (line.rsplit(':', 1) for line in fin)
dictionary = {k:int(v) for k, v in lines}
@SuziemacTani补充了一个解释和reference@LevLevitsky:如果餐馆的名字里有冒号呢?看来JonClements的回答仍然是正确的。