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

标签 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)

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

最佳答案

您需要跳过“无效”行,例如 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)

关于python - 拍卖脚本(从文件输入到字典),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22947809/

相关文章:

python - 使用 scipy 拟合给定直方图的分布

ios - 如何存储嵌套字典值

ios - 如何快速创建和添加值到字典

python - 保留 python 字典顺序 - (python dict 的延续)

python - 从字典更新列中组的值

python - 以日期为条件的每行的 Pandas 数据帧平均值

python - 在 VS Code 中本地调试多个 Python Azure 函数

c++ - std::map::iterator 在增量时使程序崩溃

python - 使用 ZipFile.extractall 时出现类型错误

python - 导入错误: No module named not_found