Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Writing to a JSON file
4. json.dumps() options—sort_keys and separators
Summary

Instruction

Excellent job! We can also sort keys or change separators inside strings when using json.dumps(). Have a look:

print(json.dumps(data, sort_keys = True, separators = (". ", " = ")))

As you can guess, the sort_keys option displays keys in alphabetical order.

Separators are the characters used to delimit key-value pairs. By default, the two separators are commas and colons (", ", ": "). We can easily define custom separators to override these defaults. In our code above, the first character (the period) separates key-value pairs from one another (e.g., separating first_name = "Guido" from last_name = "Rossum"). The last character (in the code above, the equals sign) separates keys from their values (e.g., first_name and "Guido").

Using the separators argument in this way will change our result to:

{
  "first_name" = "Guido". 
  "second_name" = "Rossum". 
  "titles" = [
    "BDFL". 
    "Developer"
  ]
}

How about trying this on your own?

Exercise

Convert the data object to a JSON format using the json.dumps() function. Sort the keys and change the separators to "; " and " = ", in that order. Print the result.