[issue38372] Undefined behavior when changing dict while iterating it

Беатрис Бонева report at bugs.python.org
Fri Oct 4 12:54:45 EDT 2019


New submission from Беатрис Бонева <beatrisvboneva at gmail.com>:

When changing a dict while iterating through it by removing one key and inserting other which is calculated based on the old one, the dict is changed unexpectedly.

The following function:

```
def test(d: dict): 
     for i in d: 
         d[i+1] = d.pop(i)
```

when called with input dict `{1: 'test'}` transforms the dict to:
- `{6: 'test'}` in Python3.7.4;
- `{8: 'test'}` in Python3.5.3 and Python2.7.

If I change the function to add 2 to the key ( `d[i+2] = d.pop(i)` ) and use the same input `{1: 'test'}` the dict is changed to:
- `{11: 'test'}` in Python3.7;
- `{9: 'test'}` in Python3.5.

Similar thing happens with strings:

```
def test(d: dict): 
     for i in d: 
         d[i+'x'] = d.pop(i)
```

When called with input dict `{'a': 'test'}` it transforms it to:
- `{'axxxxx': 'test'}` in Python3.7.4;
- `{'axx': 'test'}` in Python3.5.3.

----------
components: Library (Lib)
messages: 353954
nosy: Беатрис Бонева
priority: normal
severity: normal
status: open
title: Undefined behavior when changing dict while iterating it
type: behavior
versions: Python 2.7, Python 3.5, Python 3.6, Python 3.7

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue38372>
_______________________________________


More information about the Python-bugs-list mailing list