Bootstrap FreeKB - Python (Scripting) - Sort a Dictionary
Python (Scripting) - Sort a Dictionary

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter eea587 in the box below so that we can be sure you are a human.