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?