Python: iterate over dictionary keys by sorting
I need to iterate over the keys of a dictionary, but do so in the order indicated by the value.
Example:
myDict = {ID1: 50, ID2: 40, ID3: 60}
I would like to do this somehow:
for keyCorrespondingToTheValue in sorted(myDict.values()):
-> How can I do this?
If the value is a ranking, I want to go through each ID in the ranking order. I can do this by changing the key / values ββin the dictionary, but I don't want to because there is no guarantee that the ranking values ββare unique.
source to share
You can sort myDict.items
like this:
>>> myDict = {'ID1': 50, 'ID2': 40, 'ID3': 60}
>>> for item in sorted(myDict.items(), key=lambda x: x[1]):
... item
...
('ID2', 40)
('ID1', 50)
('ID3', 60)
>>> for key, _ in sorted(myDict.items(), key=lambda x: x[1]):
... key
...
'ID2'
'ID1'
'ID3'
>>>
The important part here is the key function sorted
that allows you to specify how you want to sort each item. In this case, we are sorting each key value.
You can also read Sort AS> in the documentation for a better understanding of how to use sorted
and key
.
source to share