【问题标题】:Dictionary counting characters - how to print alphabetically? Python [duplicate]字典计数字符 - 如何按字母顺序打印? Python [重复]
【发布时间】:2020-04-11 00:19:43
【问题描述】:

我编写了一个函数来计算文件中字符的频率。该功能按预期工作,但是,我想按键按字母顺序打印字典。我如何在 Python 中以最简单的方式做到这一点。

这是我的功能:

def characters(textfile):
    textfile=open(textfile)         
    characters={} 
    for line in textfile:
        for char in line:
            if char in characters:
                characters[char]+=1
            else:
                characters[char]=1

    print(characters)  

【问题讨论】:

标签: python sorting dictionary


【解决方案1】:

我会把它变成一个列表并对其进行排序

character_list = list(characters.items())
character_list.sort()
print(character_list)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-05
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    • 2022-11-17
    • 1970-01-01
    • 2018-01-27
    相关资源
    最近更新 更多