簡體   English   中英

如何在python中打印出txt文件的字典值的整個列表

[英]how to print out WHOLE list of dictionary values of txt file in python

我正在嘗試打印

exist = False while(exist == False):
try:
    name = input('Please enter a file name: ')
    myfile = open(name,'r')
    a = myfile.readline()
    b = myfile.readlines()
    count = len(b)
    exist = True
except:
    print('Error!', name, 'does not exist.')

myfile.close()

# converting input file into dict 
lst = list() for term in b:
    newterm = term.replace('\n','').split('\t')    #replacing with tab
    lst.append(newterm)

keylst = list()
vallst = list()

for i in range(len(lst)):
    keylst.append(lst[i][0])
    vallst.append(lst[i][1])

dict = {} 
for i in range(len(lst)):
    tempdict = {keylst[i]:vallst[i]}
    dict.update(tempdict)

這里有一堆代碼,用戶輸入等等。

這段代碼是我格式化下表的方式。

print('There are', len(dict), 'terms in the new vocabulary list.')
lst = '{0:<5} - {1:>35}'.format(newterm[0], newterm[1])
print(lst)

這里保存文件

這給了我下面的輸出:

while - Executes a block of code as long as its condition is true.

它只打印出我的 .txt 文件的最后一行/列,但我想要的是打印出整個字典。 像這樣:

term    definition
break   Used to exit a for loop or a while loop1.
continue    Used to skip the current block, and return to the "for" or "while" statement
dictionary  A mutable associative array (or dictionary) of key and value pairs. 
float   An immutable floating point number.
immutable   Cannot be changed after its created.
int An immutable integer of unlimited magnitude.
pass    Needed to create an empty code block
set Unordered set, contains no duplicates
string  Can include numbers, letters, and various symbols and be enclosed by either double or single quotes
while   Executes a block of code as long as its condition is true.

我嘗試了不同的方法,但都沒有奏效。 請幫忙

你在做一些奇怪的事情
代替

> for i in range(len(lst)):
>     keylst.append(lst[i][0])
>     vallst.append(lst[i][1])
> 
> dict = {} for i in range(len(lst)):
>     tempdict = {keylst[i]:vallst[i]}
>     dict.update(tempdict)

只需使用my_dict=dict(lst)並且不要創建名為dict變量,因為它會my_dict=dict(lst)內置函數dict
第二個問題 - 你不迭代你的字典,你只是從 newterm 輸出數據。 你需要

for term, description in my_dict.items():
    print('{0:<5} - {1:>35}'. format(term, description))

暫無
暫無

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

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