如何从.txt文件创建Python字典?

2024-06-26 14:54:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始编程,需要一些帮助。我正试图从一个.txt文件创建一个Python字典,但我不知道该怎么做。该文件的格式有数百行:

Albariño
Spanish white wine grape that makes crisp, refreshing, and light-bodied wines

理想情况下,我希望字典如下所示:

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)

请帮忙


Tags: andkeytxt字典thatlightmakeswhite
2条回答

您可以这样做,在文件的行上迭代,并使用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!'}

代码

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'}

相关问题 更多 >