Optimize dict.fromkeys() with dict inputs. Useful for resetting bag/muliset counts for example.

This commit is contained in:
Raymond Hettinger 2007-11-07 02:26:17 +00:00
parent 12e94200c0
commit cdcf887999
2 changed files with 23 additions and 0 deletions

View File

@ -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})

View File

@ -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;