繁体   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