Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Sort a dict:
- some_di = {'c': 2, 'd': 1, 'a': 4, 'b': 3}
- # noinspection PyTypeChecker
- dict_lambda = [dict(sorted(some_di.items(), key=lambda x: x[1])),
- dict(sorted(some_di.items(), key=lambda x: x[0])),
- dict(sorted(some_di.items(), key=lambda x: x[1], reverse=True)),
- dict(sorted(some_di.items(), key=lambda x: x[0], reverse=True))]
- # Or:
- import operator
- # noinspection PyTypeChecker
- dict_operator = [dict(sorted(some_di.items(), key=operator.itemgetter(1))),
- dict(sorted(some_di.items(), key=operator.itemgetter(0))),
- dict(sorted(some_di.items(), key=operator.itemgetter(1),
- reverse=True)),
- dict(sorted(some_di.items(), key=operator.itemgetter(0),
- reverse=True))]
- # Results
- print(f'Source: {some_di}',
- 'With lambda:',
- *dict_lambda,
- 'With operator:',
- *dict_operator, sep='\n')
Advertisement
Add Comment
Please, Sign In to add comment