D
D
denislysenko2021-11-26 12:35:14
Parsing
denislysenko, 2021-11-26 12:35:14

How to sort a dictionary by values ​​when the values ​​is a dictionary with tuples that are strings?

there is a dictionary in which the keys are genres, and the values ​​are dictionaries with tuples with type string in which the first element is the name of the movie, and the second element is the year of release of this movie. How to sort the values ​​​​of this dictionary so that the first tyuples are those where the newer film is, and if the years match, then by name in alphabetical order.

this is what the dictionary looks like:

{'Action': ["('Terminator Velocity', '1994')", "('Terminator 2: Judgment Day', '1991')", "('Terminator, The', '1984')", " ('Terminator 3: Rise of the Machines', '2003')", "('Terminator Salvation', '2009')", "('Terminator Genisys', '2015')"], 'Adventure': [" ('Terminator 3: Rise of the Machines', '2003')", "('Terminator Salvation', '2009')", "('Terminator Genisys', '2015')"], 'Comedy': [" ('Terminal, The', '2004')"], 'Drama': ["('Terminal, The', '2004')"], 'Mystery': ["('Terminal Velocity', '1994') "],'Romance': ["('Terminal, The', '2004')"], 'Sci-Fi': ["('Terminator 2: Judgment Day', '1991')", "('Terminator, The', '1984')", "('Terminator 3: Rise of the Machines', '2003')", "('Terminator Salvation', '2009')", "('Terminator Genisys', '2015')"] , 'Thriller': ["('Terminal Velocity', '1994')", "('Terminator, The', '1984')", "('Terminator Salvation', '2009')", "('Terminator Genisys', '2015')"]}The', '1984')", "('Terminator 3: Rise of the Machines', '2003')", "('Terminator Salvation', '2009')", "('Terminator Genisys', '2015' )"], 'Thriller': ["('Terminal Velocity', '1994')", "('Terminator, The', '1984')", "('Terminator Salvation', '2009')", " ('Terminator Genisys', '2015')"]}The', '1984')", "('Terminator 3: Rise of the Machines', '2003')", "('Terminator Salvation', '2009')", "('Terminator Genisys', '2015' )"], 'Thriller': ["('Terminal Velocity', '1994')", "('Terminator, The', '1984')", "('Terminator Salvation', '2009')", " ('Terminator Genisys', '2015')"]}"('Terminator Salvation', '2009')", "('Terminator Genisys', '2015')"]}"('Terminator Salvation', '2009')", "('Terminator Genisys', '2015')"]}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Kuts, 2021-11-26
@denislysenko

If you need to sort the entire dictionary, run through data.keys()... :

import ast
data = {
    'Action': [...],
    ...
}
sorted(map(ast.literal_eval, data['Action']), key=lambda x:(x[1], x[0]), reverse=True)

# [('Terminator Genisys', '2015'),
#  ('Terminator Salvation', '2009'),
#  ('Terminator 3: Rise of the Machines', '2003'),
#  ('Terminal Velocity', '1994'),
#  ('Terminator 2: Judgment Day', '1991'),
#  ('Terminator, The', '1984')]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question