diff --git a/tabulate.py b/tabulate.py index 454d464b..5f955eee 100755 --- a/tabulate.py +++ b/tabulate.py @@ -1052,10 +1052,14 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): uniq_keys.update(keys) rows = rows[1:] for row in rows: + list_pos = 0 for k in row.keys(): - # Save unique items in input order - if k not in uniq_keys: - keys.append(k) + # Save unique items in dictionary order + if k in uniq_keys: + list_pos = keys.index(k) + else: + list_pos += 1 + keys.insert(list_pos, k) uniq_keys.add(k) if headers == "keys": headers = keys diff --git a/test/test_input.py b/test/test_input.py index 5443ab96..ec16e590 100644 --- a/test/test_input.py +++ b/test/test_input.py @@ -407,11 +407,11 @@ def test_list_of_dicts_with_missing_keys(): lod = [{"foo": 1}, {"bar": 2}, {"foo": 4, "baz": 3}] expected = "\n".join( [ - " foo bar baz", + " foo baz bar", "----- ----- -----", " 1", - " 2", - " 4 3", + " 2", + " 4 3", ] ) result = tabulate(lod, headers="keys")