Why Python didn't throw RuntimeError: dictionary changed size during iteration, while python3 did?

Viewed 43
dict = {"a": 1, "b": 2, "c": 3, "d": 4}
for key, val in dict.items():
    if key == "b":
        dict["e"] = 5
for key, val in dict.items():
    print (key, val)

above code when executed in python3 it shows following error

RuntimeError: dictionary changed size during iteration
    for key, val in dict.items():
Line 4 in solve (Solution.py)
    ret = Solution().solve(param_1, param_2)
Line 33 in _driver (Solution.py)
    _driver()
Line 44 in <module> (Solution.py)

Where as the above code runs without error in python(version earlier that 3) and with following expected output.

('a', 1)
('c', 3)
('b', 2)
('e', 5)
('d', 4)

Is it due to this? As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

0 Answers
Related