summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2016-08-30 19:35:50 (GMT)
committerRaymond Hettinger <python@rcn.com>2016-08-30 19:35:50 (GMT)
commit43ca4528873b8d0bc8c9e63b3871f4fe4286259c (patch)
tree1b2f178f1b92934b39ac82a7279c4634a9d87c83 /Lib
parent15f44ab043b37c064d6891c7864205fed9fb0dd1 (diff)
downloadcpython-43ca4528873b8d0bc8c9e63b3871f4fe4286259c.zip
cpython-43ca4528873b8d0bc8c9e63b3871f4fe4286259c.tar.gz
cpython-43ca4528873b8d0bc8c9e63b3871f4fe4286259c.tar.bz2
Issue #27842: The csv.DictReader now returns rows of type OrderedDict.
Diffstat (limited to 'Lib')
-rw-r--r--Lib/csv.py3
-rw-r--r--Lib/test/test_csv.py16
2 files changed, 18 insertions, 1 deletions
diff --git a/Lib/csv.py b/Lib/csv.py
index 90461db..2e2303a 100644
--- a/Lib/csv.py
+++ b/Lib/csv.py
@@ -11,6 +11,7 @@ from _csv import Error, __version__, writer, reader, register_dialect, \
__doc__
from _csv import Dialect as _Dialect
+from collections import OrderedDict
from io import StringIO
__all__ = ["QUOTE_MINIMAL", "QUOTE_ALL", "QUOTE_NONNUMERIC", "QUOTE_NONE",
@@ -116,7 +117,7 @@ class DictReader:
# values
while row == []:
row = next(self.reader)
- d = dict(zip(self.fieldnames, row))
+ d = OrderedDict(zip(self.fieldnames, row))
lf = len(self.fieldnames)
lr = len(row)
if lf < lr:
diff --git a/Lib/test/test_csv.py b/Lib/test/test_csv.py
index e97c9f3..9df4080 100644
--- a/Lib/test/test_csv.py
+++ b/Lib/test/test_csv.py
@@ -10,6 +10,7 @@ import csv
import gc
import pickle
from test import support
+from itertools import permutations
class Test_Csv(unittest.TestCase):
"""
@@ -1092,6 +1093,21 @@ class TestUnicode(unittest.TestCase):
fileobj.seek(0)
self.assertEqual(fileobj.read(), expected)
+class KeyOrderingTest(unittest.TestCase):
+
+ def test_ordering_for_the_dict_reader_and_writer(self):
+ resultset = set()
+ for keys in permutations("abcde"):
+ with TemporaryFile('w+', newline='', encoding="utf-8") as fileobject:
+ dw = csv.DictWriter(fileobject, keys)
+ dw.writeheader()
+ fileobject.seek(0)
+ dr = csv.DictReader(fileobject)
+ kt = tuple(dr.fieldnames)
+ self.assertEqual(keys, kt)
+ resultset.add(kt)
+ # Final sanity check: were all permutations unique?
+ self.assertEqual(len(resultset), 120, "Key ordering: some key permutations not collected (expected 120)")
class MiscTestCase(unittest.TestCase):
def test__all__(self):