如果按键值对它进行相同排序,我将如何按值对此字典进行排序?

时间:2014-11-16 04:59:24

标签: python dictionary

# Imports the sys library
import sys
# Returns the file's contents
def readFile():
    return open("gettysburg.txt", "r").read()
# Writes to the file with the variable output
def writeFile(output):
    open("out.out", "w").write(output)
# Returns all of the words of the variable content by splitting the string by the space
def getWords(content):
    return content.replace("--", " ").replace("\n", " ").replace(".", "").replace("!", "").replace(",", "").replace("?", "").split(" ")
def main():
    # Initiates a HashMap
    wordCounts = dict()
    for text in getWords(readFile()):
        # Checks if the string is empty
        if (text != ""):
            # If the text is not in variable wordCounts then add it to the wordCounts makes it = 1 else then increment it by 1
            if (not text in wordCounts):
                wordCounts[text] = 1
            else:
                wordCounts[text] = wordCounts[text] + 1
    print(wordCounts)
    for i in range(0, 9):
        print(sorted(wordCounts, key=wordCounts.__getitem__, reverse=True)[i])
main()

我如何按值对wordCounts进行排序,然后按键对其进行排序?

我不能使用任何类型的库,所以请不要建议使用库来提高效率。

我有点难过这个。

对我正在做的事情有所了解:

基本上我找到一个带有文本块的单词频率,并根据值按字母顺序打印出来。

2 个答案:

答案 0 :(得分:1)

d = dict()
d["a"] = 10
d["ab"] = 8
d["abc"] = 10
d["bc"] = 9

for value, key in sorted(zip(d.values(), d.keys())):
    print(value, key)

输出:

8 ab
9 bc
10 a
10 abc

答案 1 :(得分:0)

这是您要找的输出吗?

d = dict()

d['that']= 13
d['the']=9
d['to']=8
d['we']=8
d['here']=8
d['a']=7
d['and']=6
d['nation']=5
d['not']=5
d['for']=5
d['can']=5
d['of']=5
d['have']=5

ordered = dict()
for e in d:
  if d[e] not in ordered:
    ordered[d[e]] = []
  ordered[d[e]].append(e)

for e in reversed(sorted(ordered.keys())):
  for v in sorted(ordered[e]):
    print e, v

输出:

13 that
9 the
8 here
8 to
8 we
7 a
6 and
5 can
5 for
5 have
5 nation
5 not
5 of