Commits

Sergey Astanin committed 1807d98 Merge

Merged in mkocikowski/python-tabulate-namedtuple (pull request #3)

Support for list of namedtuple 'keys'.

Comments (0)

Files changed (2)

             getattr(tabular_data.dtype, "names")):
             # numpy record array
             headers = tabular_data.dtype.names        
+        elif (headers == "keys" 
+              and len(rows) > 0 
+              and isinstance(rows[0], tuple) 
+              and hasattr(rows[0], "_fields")): # namedtuple
+            headers = list(map(_text_type, rows[0]._fields))
         elif headers == "keys" and len(rows) > 0:  # keys are column indices
             headers = list(map(_text_type, range(len(rows[0]))))
 
     except ImportError:
         print("test_pandas_keys is skipped")
         pass   # this test is optional
+
+
+def test_list_of_namedtuples(): 
+    "List of named tuples with field names as headers." 
+    from collections import namedtuple
+    NT = namedtuple("NT", ['foo', 'bar'])
+    lt = [NT(1,2), NT(3,4)]
+    expected = u'  foo    bar\n-----  -----\n    1      2\n    3      4'
+    result = tabulate(lt, headers="keys")
+    assert expected == result