python - 拍卖脚本(从文件到字典的输入)

时间:2014-04-08 20:45:50

标签: python dictionary

所以我有一个文件,例如:

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)

那么,如何正确读取数据?

1 个答案:

答案 0 :(得分:2)

你需要跳过"无效"像BookNotebook这样的行:

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)