所以我有一个文件,例如:
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)
那么,如何正确读取数据呢?
最佳答案
您需要跳过“无效”行,例如 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)
关于python - 拍卖脚本(从文件输入到字典),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22947809/