【问题标题】:How to sort a dictionary alphabetically?如何按字母顺序对字典进行排序?
【发布时间】:2017-03-21 21:01:28
【问题描述】:
def wordCount(inPath):
    inFile = open(inPath, 'r')
    lineList = inFile.readlines()
    counter = {}
    for line in range(len(lineList)):
        currentLine = lineList[line].rstrip("\n")
        for letter in range(len(currentLine)):
            if currentLine[letter] in counter:
                counter[currentLine[letter]] += 1
            else:
                counter[currentLine[letter]] = 1

    sorted(counter.keys(), key=lambda counter: counter[0])
    for letter in counter:
        print('{:3}{}'.format(letter, counter[letter]))

inPath = "file.txt"
wordCount(inPath)

这是输出:

a  1
k  1
u  1
l  2
   12
h  5
T  1
r  4
c  2
d  1
s  5
i  6
o  3
f  2
H  1
A  1
e  10
n  5
x  1
t  5

这是我想要的输出:

  12
A 1
H 1
T 1
a 1
c 2
d 1
e 10
f 2
h 5
i 6
k 1
l 2
n 5
o 3
r 4
s 5
t 5
u 1
x 1

如何按字母顺序对“计数器”进行排序? 我试过简单地按键和值排序,但它没有按字母顺序返回它,首先从大写字母开始 感谢您的帮助!

【问题讨论】:

标签: python sorting dictionary alpha


【解决方案1】:
sorted(counter.keys(), key=lambda counter: counter[0])

单独什么都不做:它返回一个根本不使用的结果(除非您使用 _ 回忆它,但那是一种命令行实践)

与使用list.sort() 方法可以执行的操作相反,您不能“就地”对字典键进行排序。但是你可以做的是迭代键的排序版本:

for letter in sorted(counter.keys()):

, key=lambda counter: counter[0]在这里没用:你的钥匙里只有字母。

另外:您的整个代码可以使用collections.Counter 来计算字母大大简化。

import collections

c = collections.Counter("This is a Sentence")
for k,v in sorted(c.items()):
    print("{} {}".format(k,v))

结果(包括空格字符):

  3
S 1
T 1
a 1
c 1
e 3
h 1
i 2
n 2
s 2
t 1

【讨论】:

  • 不用将他的数据存储在字典中,他也可以只使用 OrderedDict,这样他就不必在每次打印时都对 counter.keys() 进行排序
  • OrderedDict 跟踪插入顺序。这和排序不是一回事。如果顺序不是排序顺序,排序会破坏顺序。
  • print(k, v) 怎么样?
  • @StefanPochmann:在 python 2 中,它会将k,v 打印为tuple(除非您从__futures__ 导入print_function),因此使用format `is version agnostic.
  • 感谢您对代码的分解和简化。只是我们没有学过收藏,所以虽然我很想简单地使用你更简单的解决方案,但我真的不明白发生了什么。
猜你喜欢
  • 2013-04-03
  • 2018-01-27
  • 1970-01-01
  • 2020-11-26
  • 1970-01-01
  • 2021-12-20
  • 2014-01-26
  • 1970-01-01
相关资源
最近更新 更多