簡體   English   中英

如何從 .t​​xt 文件制作 Python 字典?

[英]How do I make a Python dictionary from .txt file?

我是編程新手,需要一些幫助。 我正在嘗試從 .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)

請幫忙

您可以這樣做,迭代文件的行並使用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'}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM