所以我有一个文件,例如:
Book
Peter 500
George Peterson 300
Notebook
Lizzie 900
Jack 700
整数是他们对奖品的出价。我想阅读字典的名称和出价,但我被困在这里:
d = {}
with open('adat.txt') as f:
d = dict(x.rstrip().split(None, 1) for x in f)
for keys,values in d.items():
print(keys)
print(values)
那么,如何正确读取数据?
答案 0 :(得分:2)
你需要跳过"无效"像Book
和Notebook
这样的行:
d = {}
with open('adat.txt') as f:
for line in f:
words = line.split()
try:
price = int(words[-1])
name = ' '.join(words[:-1])
d[name] = price
except (ValueError, IndexError):
# line doesn't end in price (int() raised ValueError)
# or is empty (words[-1] raised IndexError)
pass
for key, value in d.items():
print(key)
print(value)