Building a list of dictionary values, sorted by key

This code:

keys = sorted(attributes.keys(), reverse=True)
result = []
for key in keys:
    result.append(attributes[key])

Is basically the use case for which list comprehensions were invented:

result = [attributes[key] for key in sorted(attributes.keys(), reverse=True)]

Leave a Comment

File not found.