Python (Scripting) - Sort a Dictionary
                
            
            
            
            
            
            
                           
                
            
            
            
                
    
    
    
            
                
                    by
                    Jeremy Canfield  |  
                    Updated: November 06 2023
                    
                          |  Python (Scripting) articles
                    
                    
                    
                
            
            Here is an example of how you can create a dictionary.
#!/usr/bin/python3
dictionary = {
  "foo": "Hello",
  "bar": "World"
}
for key in dictionary:
  print(f"{key} = {dictionary[key]}")
Which should print the following. Notice the output is not sorted alphabetically.
foo = Hello
bar = World
sorted can be used to sort the dictionary alphabetically.
#!/usr/bin/python3
dictionary = {
  "foo": "Hello",
  "bar": "World"
}
for key in sorted(dictionary):
  print(f"{key} = {dictionary[key]}")
And now the output is sorted alphabetically.
bar = World
foo = Hello
Did you find this article helpful?
If so, consider buying me a coffee over at 