Sorting both the keys and values(list) in dcitionary | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Sorting both the keys and values(list) in dcitionary

#I have a function which takes 2 parameters, a string and a dictionary. The string will represent the filename to which to write. The keys in the dictionary will be strings representing movie titles. The values in the dictionary will be lists of strings representing performers in the corresponding movie. The function should write the list of movies to the file given by the filename using the following format: # Title: Actor 1, Actor 2, Actor 3, etc. #The movies and the actor names should be sorted alphabetically. #Write your function here! def write_movie_info(filename, movies): _file = open(filename, "a") for key,values in movies.items(): _file.write(str(key) + ":" + " ") i = 1 for each_value in values: if i < len(values): _file.write(str(each_value) + ','+" ") else: _file.write(str(each_value)) i += 1 _file.write('\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) ***************************** The expected result is : # Chocolat: Alfred Molina, Johnny Depp, Judi Dench, Juliette Binoche # Skyfall: Daniel Craig, Javier Bardem, Judi Dench, Naomie Harris but my code is printing: #Chocolat: Juliette Binoche, Judi Dench, Johnny Depp, Alfred Molina #Skyfall: Judi Dench, Daniel Craig, Javier Bardem, Naomie Harris Please help me in sorting both the keys and values list alphabetically. I tried sort, sorted but it doesnt work.

19th Oct 2020, 1:38 AM
NG_
NG_ - avatar
4 Answers
+ 1
I would very much appreciate it if you would save that code in SoloLearn and share the code link instead. A code is easier to look and analyse than raw text like this. You may also copy the description into the code so one can look back at it, in case they forget something. Lastly, in case you didn't know how, here's a guide to sharing links 👇 https://www.sololearn.com/post/75089/?ref=app
19th Oct 2020, 4:00 AM
Ipang
+ 1
https://code.sololearn.com/cMXQ5yVC44h9/?ref=app Here's how you do it
19th Oct 2020, 4:28 AM
Hima
Hima - avatar
+ 1
https://code.sololearn.com/cMAcjbqZ3NgT/#py Here is the link to my code.
19th Oct 2020, 5:05 AM
NG_
NG_ - avatar
+ 1
Here is an edited version of your code. https://code.sololearn.com/cFoRhK36jasD/?ref=app
19th Oct 2020, 8:43 AM
Ipang