不能将python中的dictionary作为返回格式正确的函数打印

2024-09-28 13:02:24 发布

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

我创建了一个可以工作的函数,但是我不能让它以所需的格式返回输出。你知道吗

我的代码:

def readingjunk(filename):
    infile = open(filename, "r")
    dicty = {} 
    for line in infile:
          words = line.split()
          words = line.rsplit()
          #words = getWord(words)
          #print(words)
          for word in words :
                if word not in dicty:
                      dicty[word] = 1
    dicty.pop("/#")
    dicty.pop("#/")
    dicty2 = {}
    nobr = []
    for item in dicty.items():
          if(item[0] == getWord(item[0])):
             #print(item[0])
             nobr.append(item[0])
             dicty2[item[0]] = 1
    #nobr = str(nobr)
    #nobr.lower()
    #for item in dicty2.items() :
     #     print(item[0])  
    #print(dicty2)
    infile.close()
    return(print(dicty2))

输出如下所示:

{'A': 1, 'B': 1, 'C': 1, "D": 1, "E": 1}

我希望输出按字母顺序和小写字母显示如下:

a
b
c
d
e

我试过逃避,但需要帮助。你知道吗


Tags: inforiflinefilenameitempopinfile
1条回答
网友
1楼 · 发布于 2024-09-28 13:02:24

您可以使用以下方式打印输出:

dicty2 = {'A': 1, 'B': 1, 'C': 1, "D": 1, "E": 1}
for key in sorted(dicty2.keys()):
    print(key.lower())

请不要使用下面的代码。

评论基于:

[print(key.lower()) for key in sorted(dicty2.keys())]

相关问题 更多 >

    热门问题