如何从.txt文件制作Python字典?

时间:2020-04-02 18:36:00

标签: python dictionary

我是编程新手,需要一些帮助。我正在尝试从.txt文件创建Python字典,但不确定如何处理。该文件的格式有数百行:

dictionary1 = {key:value}
dictionary1 = {"Albariño":"Spanish white wine grape that makes crisp, refreshing, and light-bodied wines"}

理想情况下,我希望字典看起来像这样:

dictionary1 = {}
with open("list_test.txt", 'r') as f:
    for line in f:
        (key, val) = line.splitlines()
        dictionary1[key] = val
print(dictionary1)

这就是我一直在尝试的工作:

{{1}}

请帮助

2 个答案:

答案 0 :(得分:1)

您可以这样操作,在文件的各行上进行迭代,并使用next()在同一循环中获取下一行的描述:

dictionary1 = {}
with open("list_test.txt", 'r') as f:
    for line in f:
        key = line.strip()
        val = next(f).strip()
        dictionary1[key] = val
print(dictionary1)

# {'Albariño': 'Spanish white wine grape that makes crisp, refreshing, and light-bodied wines', 
#  'Some other wine': 'Very enjoyable!'}

答案 1 :(得分:0)

代码

with open("list_test.txt", 'r') as f:
  lines = f.read().split('\n')
  dict1 = {x.rstrip():y.rstrip() for x, y in zip(lines[0::2], lines[1::2])}

测试

import pprint
pprint.pprint(dict1)

测试文件 list_test.txt

lbariño
Spanish white wine grape that makes crisp, refreshing, and light-bodied wines
fred
Italian red wine
Maria
French wine

输出

{'Maria': 'French wine',
 'fred': 'Italian red wine',
 'lbariño': 'Spanish white wine grape that makes crisp, refreshing, and '
            'light-bodied wines'}