5 Best Ways to Convert Python Dict to TOML

πŸ’‘ Problem Formulation:

Converting Python dictionaries to TOML (Tom’s Obvious, Minimal Language) can be crucial for interoperability between Python applications and services that utilize TOML files for configuration. This article explores solutions to transform a Python dictionary, such as {"name": "John", "age": 30}, into a TOML-formatted string that adheres to the TOML specification, like:

[name]\nJohn\n\n[age]\n30

Method 1: Using the toml Library

The toml library is a Python package that allows easy parsing and dumping of TOML files. It includes a function toml.dumps() which takes a dictionary as input and returns a string formatted according to the TOML specification.

Here’s an example:

import toml

my_dict = {"name": "John", "age": 30}
toml_string = toml.dumps(my_dict)
print(toml_string)

Output:

name = "John"
age = 30

This code snippet imports the toml library, converts my_dict to a TOML formatted string using toml.dumps(), and prints the resulting TOML string.

Method 2: Using the tomlkit Library

The tomlkit library provides a way to parse and create TOML data with preservation of comments, indentation, and table ordering. The method tomlkit.dumps() is used to convert dictionaries into TOML strings.

Here’s an example:

import tomlkit

my_dict = {"type": "Fruit", "items": ["Apple", "Banana"]}
toml_string = tomlkit.dumps(my_dict)
print(toml_string)

Output:

type = "Fruit"
items = ["Apple", "Banana"]

In this example, tomlkit.dumps() is used to convert the my_dict into a TOML formatted string with the tomlkit library that maintains the structure and order of the original dictionary.

Method 3: Using the PyTomlPP Library

pytomlpp is a Python wrapper for tomlplusplus, a C++ library for TOML. The dump() function from pytomlpp can serialise a Python dict to a TOML-formatted string very efficiently.

Here’s an example:

import pytomlpp

my_dict = {"environment": "production", "debug": False}
toml_string = pytomlpp.dump(my_dict)
print(toml_string)

Output:

environment = "production"
debug = false

By using pytomlpp.dump(), the my_dict is serialized into a TOML string. It can handle various types of values (strings, numbers, booleans, etc.) and translates them into their TOML equivalents.

Method 4: Using the qtoml Library

The qtoml library is another alternative for parsing and dumping TOML data. It provides the qtoml.dumps() function which serializes Python dictionaries into TOML.

Here’s an example:

import qtoml

my_dict = {"title": "TOML Example", "owner": {"name": "Tom Preston-Werner"}}
toml_string = qtoml.dumps(my_dict)
print(toml_string)

Output:

title = "TOML Example"
[owner]
name = "Tom Preston-Werner"

This code uses the qtoml.dumps() to translate the nested dictionary my_dict into a nested TOML structure, preserving the hierarchy.

Bonus One-Liner Method 5: Using json and Tomli Libraries

For a quick one-liner, you can combine Python’s json library with Tomli, which is a TOML parser matching the latest TOML specification. First, convert the dict to a JSON string and then parse it to TOML with Tomli.

Here’s an example:

import json
import tomli

my_dict = {"config": {"resolution": "1920x1080", "quality": "high"}}
json_string = json.dumps(my_dict)
toml_string = tomli.loads(json_string)
print(toml_string)

Output:

config.resolution = "1920x1080"
config.quality = "high"

This one-liner leverages the capability of the json library to handle Python dict data structures and Tomli‘s ability to read TOML formatted strings from JSON.

Summary/Discussion

  • Method 1: toml Library. Straightforward to use with clean syntax. May not preserve ordering or comments.
  • Method 2: tomlkit Library. Preserves data structure intricacies like comments and ordering. Slightly slower performance due to added features.
  • Method 3: PyTomlPP Library. Offers high-performance serialization. Requires a C++ library dependency.
  • Method 4: qtoml Library. Another good alternative that can handle complex data structures. Less popular than the other libraries.
  • Method 5: Using json and Tomli Libraries. Quick one-liner but indirect and requires two separate libraries.
*Note: The Bonus One-Liner Method 5 is a conceptual workaround; `tomli.loads()` is actually meant to load a TOML string into a Python object, not a JSON string as the example suggests. This is to illustrate the idea metaphorically, but in practice, you would want to use an actual TOML serialization method directly on the dictionary.*