【问题标题】:How to make a dictionary from a txt file?如何从txt文件制作字典?
【发布时间】:2021-12-29 14:06:21
【问题描述】:

假设以下文本文件 (dict.txt) 有

1    2    3
aaa  bbb  ccc

字典应该是{1: aaa, 2: bbb, 3: ccc} 这样的

我做到了:

d = {}
with open("dict.txt") as f:
for line in f:
    (key, val) = line.split()
    d[int(key)] = val

print (d)

但它没有用。我认为是因为txt文件的结构。

【问题讨论】:

  • 读取第一行并拆分。阅读第二行并拆分。然后:How do I convert two lists into a dictionary?
  • 这是一个非常丑陋的文件格式定义。您确定不能更改文件的写入方式吗?
  • 为什么不使用 JSON 或类似 INI 的配置文件?,有一个可用于 INI 格式的解析器:docs.python.org/3/library/configparser.html
  • with open("dict.txt") as f: d = dict(zip(map(int, next(f).split()), next(f).split())).

标签: python dictionary txt key-value-store


【解决方案1】:

你想成为键的数据在第一行,你想成为值的所有数据都在第二行。
所以,做这样的事情:

with open(r"dict.txt") as f: data = f.readlines() # Read 'list' of all lines

keys = list(map(int, data[0].split()))            # Data from first line
values = data[1].split()                          # Data from second line

d = dict(zip(keys, values))                       # Zip them and make dictionary
print(d)                                          # {1: 'aaa', 2: 'bbb', 3: 'ccc'}

【讨论】:

    【解决方案2】:

    根据 OP 编辑​​更新答案:

    #Initialize dict
    d = {}
    
    #Read in file by newline splits & ignore blank lines
    fobj = open("dict.txt","r")
    lines = fobj.read().split("\n")
    lines = [l for l in line if not l.strip() == ""]
    fobj.close()
    
    #Get first line (keys)
    key_list = lines[0].split()
    
    #Convert keys to integers
    key_list = list(map(int,key_list))
    
    #Get second line (values)
    val_list = lines[1].split()
    
    #Store in dict going through zipped lists
    for k,v in zip(key_list,val_list):
        d[k] = v
    
        
    

    【讨论】:

    • 为什么要放在一行中? OP 有 2 行。这显然也不是场景 2。
    • @ThomasWeller 是的,OP 在我回复后才更新了他原始问题的格式。原来是在一条线上问的。
    • @ThomasWeller 进行了相应编辑
    • 根据 OP 的尝试,似乎键应该是整数
    【解决方案3】:

    首先为键和值创建单独的列表,带有条件 喜欢:

        if (idx % 2) == 0:
            keys = line.split()
            values = lines[idx + 1].split()
    
    

    然后合并两个列表

    d = {}
    
    # Get all lines in list
    with open("dict.txt") as f:
        lines = f.readlines()
    
    for idx, line in enumerate(lines):
        if (idx % 2) == 0:
            # Get the key list
            keys = line.split()
    
            # Get the value list
            values = lines[idx + 1].split()
    
            # Combine both the lists in dictionary
            d.update({ keys[i] : values[i] for i in range(len(keys))})
    print (d)
    
    

    【讨论】:

    • 如果你不使用 d.update 而不是进行赋值,那么在每次迭代时它都会被覆盖。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-12
    • 2017-04-24
    • 2020-06-01
    • 2021-07-21
    • 1970-01-01
    相关资源
    最近更新 更多