This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: dictionary creation error
Type: behavior Stage: resolved
Components: Versions:
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: TobiasHT, steven.daprano
Priority: normal Keywords:

Created on 2021-12-28 10:00 by TobiasHT, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (2)
msg409251 - (view) Author: TobiasHT (TobiasHT) * Date: 2021-12-28 10:00
I was creating a dictionary when I noticed something weird.
I had a function responsible for creating dictionary keys and then values were assigned to the keys in a for loop.
The code goes a little like this:

>>> def key_maker(n):
...     if (n % 2) == 0:
...         return n
...     return None

>>> dictionary = {}
>>> for i in range(10):
...     dictionary[key_maker(i)] = i if key_maker(i) else "error"

>>> dictionary
{0: 'error', None: 'error', 2: 2, 4: 4, 6: 6, 8: 8}


when I tried to print out the rest of the values in the "else" clause,
I realized that 0 appeared there as well, so 0 appeared twice.

>>> for i in range(10):
...     dictionary[key_maker(i)] = i if key_maker(i) else print(i)
...
0
1
3
5
7
9
>>> dictionary
{0: 'error', None: 'error', 2: 2, 4: 4, 6: 6, 8: 8}

I still can not figure out why the first two elements are inconsistent
from the rest of the dictionary, and why they appear in the first place.
msg409252 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2021-12-28 10:12
> I still can not figure out why the first two elements are inconsistent
from the rest of the dictionary, and why they appear in the first place.

Hi Tobias,

This is a bug tracker for reporting bugs in Python, not a help desk to ask for explanations. The behaviour you see is correct. Except for the last line, which is a copy-and-paste error on your part: the actual last line is

>>> dictionary
{0: None, None: None, 2: 2, 4: 4, 6: 6, 8: 8}

So there is no error here, everything is working as expected.

If you need help understanding why the code is correct, please take the discussion to the Python Discuss forum where you will be sure to get answers.
History
Date User Action Args
2022-04-11 14:59:53adminsetgithub: 90346
2021-12-28 10:12:39steven.dapranosetstatus: open -> closed

nosy: + steven.daprano
messages: + msg409252

resolution: not a bug
stage: resolved
2021-12-28 10:00:02TobiasHTcreate