Philip Adams
Philip Adams

Reputation: 13

How to sort the keys of a dictionary alpabetically

I want to take a dictionary, where the key is a string and the value a list of strings, and be able to print it in a new file where the keys are alphabetized, as well as the values. I'm not having any issue with the values. The problem lies in figuring out how to get the keys to print in the file alphabetically. Here is what I have:

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

and the dictionary is:

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)

Upvotes: 1

Views: 446

Answers (3)

bharatk
bharatk

Reputation: 4315

OrderedDict() could be used to maintain the insertion-ordering, once the keys are sorted.

Ex.

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

Upvotes: 0

BugHunter
BugHunter

Reputation: 1204

You can use sorted method to sort your dictionary using key

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

and you can directly iterate it.

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

Upvotes: 1

Mark
Mark

Reputation: 92440

Rather than iterating over the dictionary, you can iterate over its sorted keys created with:

sorted(aDict.keys())

Here's the function modified to just print the list:

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)

Prints:

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

Upvotes: 1

Related Questions