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.

+3


source to share


3 answers


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

.

+4


source


for key in sorted(myDict, key=myDict.get)

      



+4


source


for key in sorted(myDict, key=lambda k: myDict[k]):
    ...

      

+2


source







All Articles