summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2007-11-07 02:26:17 (GMT)
committerRaymond Hettinger <python@rcn.com>2007-11-07 02:26:17 (GMT)
commitcdcf887999524cb7ff5ba3cab129d04956333e0d (patch)
treea97698d11da0e0a5450f5ab4a6647520db0d1a11
parent12e94200c0b12487e129ce7e325d9315c12ca88a (diff)
downloadcpython-cdcf887999524cb7ff5ba3cab129d04956333e0d.zip
cpython-cdcf887999524cb7ff5ba3cab129d04956333e0d.tar.gz
cpython-cdcf887999524cb7ff5ba3cab129d04956333e0d.tar.bz2
Optimize dict.fromkeys() with dict inputs. Useful for resetting bag/muliset counts for example.
-rw-r--r--Lib/test/test_dict.py4
-rw-r--r--Objects/dictobject.c19
2 files changed, 23 insertions, 0 deletions
diff --git a/Lib/test/test_dict.py b/Lib/test/test_dict.py
index 7f0aabb..9f049ad 100644
--- a/Lib/test/test_dict.py
+++ b/Lib/test/test_dict.py
@@ -243,6 +243,10 @@ class DictTest(unittest.TestCase):
self.assertRaises(Exc, baddict2.fromkeys, [1])
+ # test fast path for dictionary inputs
+ d = dict(zip(range(6), range(6)))
+ self.assertEqual(dict.fromkeys(d, 0), dict(zip(range(6), [0]*6)))
+
def test_copy(self):
d = {1:1, 2:2, 3:3}
self.assertEqual(d.copy(), {1:1, 2:2, 3:3})
diff --git a/Objects/dictobject.c b/Objects/dictobject.c
index 9b99bbf..00f9bc8 100644
--- a/Objects/dictobject.c
+++ b/Objects/dictobject.c
@@ -1184,6 +1184,25 @@ dict_fromkeys(PyObject *cls, PyObject *args)
if (d == NULL)
return NULL;
+ if (PyDict_CheckExact(d) && PyDict_CheckExact(seq)) {
+ PyDictObject *mp = (PyDictObject *)d;
+ PyObject *oldvalue;
+ Py_ssize_t pos = 0;
+ PyObject *key;
+ long hash;
+
+ if (dictresize(mp, ((PyDictObject *)seq)->ma_used))
+ return NULL;
+
+ while (_PyDict_Next(seq, &pos, &key, &oldvalue, &hash)) {
+ Py_INCREF(key);
+ Py_INCREF(value);
+ if (insertdict(mp, key, hash, value))
+ return NULL;
+ }
+ return d;
+ }
+
if (PyDict_CheckExact(d) && PyAnySet_CheckExact(seq)) {
PyDictObject *mp = (PyDictObject *)d;
Py_ssize_t pos = 0;