Sunday 27 December 2020

Python: Looping through the dictionary in the sorted order of keys

Using ‘sorted’ and ‘keys’ methods, you can loop through the dictionary in the sorted order of dictionary keys.

>>> country_capitals = {"India" : "New Delhi", "Bangladesh" : "Dhaka", "France" : "Paris"}
>>> 
>>> for country in sorted(country_capitals):
...    print(f"{country} -> {country_capitals[country]}")
... 
Bangladesh -> Dhaka
France -> Paris
India -> New Delhi

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment