【问题标题】:how to insert values to a dictionary from a file如何将值从文件插入字典
【发布时间】:2020-03-25 09:00:59
【问题描述】:

我需要存储来自 1 个文件的键和来自另一个文件的值。就像从第一个文件中一样,该文件的第一行是“a”,第二个文件的第一行是 20。字典应该是 a:20

【问题讨论】:

  • 从两个文件中并行读取行并构造字典。 open, for, zip 是你的朋友。
  • 你可以试试` paste -d : 1.txt 2.txt`

标签: python dictionary file-handling


【解决方案1】:

试试这样的:

dictionary = {}
with open("file1.txt") as file1, open("file2.txt") as file2:
    for key, value as zip(file1, file2):
        key = key.strip()
        value = value.strip() # If all the values must be integers, do int(value.strip())
        dictionary[key] = value

【讨论】:

    猜你喜欢
    • 2021-12-13
    • 2021-12-24
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多