Sorting Python Dictionary

Asked 2 years ago, Updated 2 years ago, 49 views

I'd like to sort to a non-key value in dict Read two fields (string value, numerical value, one by one) in the DB x = {'1': 2, '3': 4, '4': 3, '2': 1, '0': 0} I made it. String is a unique key and numeric is not. I can sort it based on string, but I don't know how to sort it in numeric. What should I do?

sorting python

2022-09-21 19:46

1 Answers

Unlike the list or tuple, dict has no order. Therefore, the dict type cannot be sorted, so if you want to sort the dict, you have to express it as a list of tuples.

For example. I want to set it at a price other than a keyCotton

import operator
x = {'1': 2, '3': 4, '4': 3, '2': 1, '0': 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))

In this case, sorted_x is a list of tuples sorted based on the second element.

dict(sorted_x) is equal to x.

If you want to sort by key, you can write:

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))


2022-09-21 19:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.