'How to convert a Markdown table from horizontal display to vertical in Python?

My code is this:

from tomark import Tomark
dict = [{ "key":"value", "key":"value", "key":"value"}]

markdown = Tomark.table(dict)
print(markdown)

The result is this:

PR Status Date Title
292 open None Adds new wiz bang feature
286 v1.0 None Updates UI to be more awesome

Does anyone have an idea of how to make the key-value pair each one in a row?

How to modify the source class to achieve that?



Solution 1:[1]

Suppose you have a single dictionary my_dict. Then Tomark will output this as a single row (values) plus header (keys):

| key_a | key_b | key_c |
|-----|-----|-----|
| value_a | value_b | value_c |

Transpose the table

Now you want to transpose the table:

  • Each column (dict item) should move to a separate row with 2 columns (key, value).
  • The 2 columns need some new names given.

For your input data this means you have to iterate through the dictionary's items and transpose each item to a new dict with 2 entries, one for each column. And you have to name the newly created columns, e.g. {"key": k, "value": v}. This new dict is added as line to a list.

from tomark import Tomark

my_dict = { "key_a":"value_a", "key_b":"value_b", "key_c":"value_c"}

transposed_list = []
for k,v in my_dict.items():
    transposed_list.append({"key": k, "value": v})

# print(transposed_list)
# [{'value': 'value_a', 'key': 'key_a'}, {'value': 'value_c', 'key': 'key_c'}, {'value': 'value_b', 'key': 'key_b'}]

markdown = Tomark.table(transposed_list)
print(markdown)

Prints:

| key | value |
|-----|-----|
| key_a | value_a |
| key_b | value_b |
| key_c | value_c |

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hc_dev