Original code copyright (C) 2009-2022 Rudolf Cardinal (

This file is part of cardinal_pythonlib.

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Trivial functions to make tab-separated value (TSV) files.

cardinal_pythonlib.tsv.dictlist_to_tsv(dictlist: List[Dict[str, Any]]) str[source]

From a consistent list of dictionaries mapping fieldnames to values, make a TSV file.

cardinal_pythonlib.tsv.make_tsv_row(values: List[Any]) str[source]

From a list of values, make a TSV line.

cardinal_pythonlib.tsv.tsv_escape(x: Any) str[source]

Escape data for tab-separated value (TSV) format.

cardinal_pythonlib.tsv.tsv_pairs_to_dict(line: str, key_lower: bool = True) Dict[str, str][source]

Converts a TSV line into sequential key/value pairs as a dictionary.

For example,



{"field1": "value1", "field2": "value2"}
  • line – the line

  • key_lower – should the keys be forced to lower case?

Sometimes we get lines that end in a tab. This is valid. Check with these:

import logging
from cardinal_pythonlib.tsv import tsv_pairs_to_dict
print(tsv_pairs_to_dict("a\t1\tb\t2\tc\t3"))  # OK
print(tsv_pairs_to_dict("a\t1\tb\t2\tc\t"))  # OK
print(tsv_pairs_to_dict("a\t1\tb\t2\tc"))  # not OK; orphan 'c'
print(tsv_pairs_to_dict("a\t1\tb\t2\tc\t\n"))  # OK

Beware using rstrip() prior to a call to this function, because that will also strip trailing tabs.