gpt4 book ai didi

python - 如何按字母顺序对字典的键进行排序

转载 作者:行者123 更新时间:2023-12-01 00:44:20 26 4
gpt4 key购买 nike

我想要一本字典,其中键是一个字符串,值是一个字符串列表,并且能够将其打印在一个新文件中,其中键和值均按字母顺序排列。我对值(value)观没有任何问题。问题在于弄清楚如何让 key 按字母顺序打印在文件中。这是我所拥有的:

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)

最佳答案

您可以迭代使用以下命令创建的排序键,而不是迭代字典:

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']]

关于python - 如何按字母顺序对字典的键进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57101123/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com