如何按字母顺序排序字典的键

时间:2019-07-18 19:03:10

标签: python sorting dictionary

我想带一个字典,键是一个字符串,值是一个字符串列表,并能够将其打印在一个新文件中,在该文件中,键和字母都按字母顺序排列。我的值没有任何问题。问题在于弄清楚如何使密钥按字母顺序打印在文件中。这是我所拥有的:

def write_movie_info(string, aDict):
    newFile = open(string, 'w')
    myList = []

    for movie in aDict:
        aDict[movie].sort()
        myList.append([movie] + aDict[movie])


    for aList in myList:
        joiner = ", ".join(aList[1:])
        newFile.write(aList[0] + ': ' + joiner + '\n')

而字典是:

movies = {"Chocolat": ["Juliette Binoche", "Judi Dench", "Johnny Depp", "Alfred Molina"], "Skyfall": ["Judi Dench", "Daniel Craig", "Javier Bardem", "Naomie Harris"]}
write_movie_info("Test.txt", movies)

3 个答案:

答案 0 :(得分:1)

除了遍历字典之外,您还可以遍历使用以下命令创建的已排序键:

sorted(aDict.keys())

这里修改了功能,只打印列表:

def write_movie_info(string, aDict):
    myList = []

    sorted_keys = sorted(aDict.keys())
    for movie in sorted_keys:
        aDict[movie].sort()
        myList.append([movie] + aDict[movie])

    print(myList)



movies = {"Lawrence of Arabia": ["Peter O'Toole", "Omar Sharif"], "Chocolat": ["Juliette Binoche", "Judi Dench", "Johnny Depp", "Alfred Molina"], "Skyfall": ["Judi Dench", "Daniel Craig", "Javier Bardem", "Naomie Harris"]}
write_movie_info("Test.txt", movies)

打印:

[['Chocolat', 'Alfred Molina', 'Johnny Depp', 'Judi Dench', 'Juliette Binoche'], ['Lawrence of Arabia', 'Omar Harif', "Peter O'Toole"], ['Skyfall', 'Daniel Craig', 'Javier Bardem', 'Judi Dench', 'Naomie Harris']]

答案 1 :(得分:1)

您可以使用sorted方法使用key来对字典进行排序

sorted(your_dict.items(), key=lambda x: x[0])

,您可以直接对其进行迭代。

for key, value in sorted(your_dict.items(), key=lambda x: x[0]):
    # do something

ref:https://docs.python.org/3/library/functions.html#sorted

答案 2 :(得分:0)

一旦对键进行排序,

OrderedDict()可用于维持插入顺序。

例如。

import collections

movies = {"Skyfall": ["Judi Dench", "Daniel Craig", "Javier Bardem", "Naomie Harris"],
"Chocolat": ["Juliette Binoche", "Judi Dench", "Johnny Depp", "Alfred Molina"]}

order_dict = collections.OrderedDict(sorted(movies.items(), key=lambda x: x[0]))
print(order_dict)

O / P:

OrderedDict([('Chocolat', ['Juliette Binoche', 'Judi Dench', 'Johnny Depp', 'Alfred Molina']), ('Skyfall', ['Judi Dench', 'Daniel Craig', 'Javier Bardem', 'Naomie Harris'])])