2

I was fiddling with dict() and found out that when I do

>>> dict({4:None}) it returns {4: None} which is expected but,

when I try converting a list containing a nested set [{4,None}]

>>> dict([{4,None}]) returns {None: 4} which genuinely unexpected.

Then I checked that it only happens with few integers. That is crazy.

e.g. dict([{5,None}]) returns {None: 5}

dict([{6,None}]) returns {None: 6}

dict([{7,None}]) returns {None: 7}

although

dict([{8,None}]) returns {8: None}

dict([{9,None}]) returns {9: None}

Can anyone answer this? I am using Python 3.11

  • `{4,None}` is a `set` of 4 and None. A Set is an unordered collection of data. It might be better to use list of tuple or list, e.g. `dict([(4,None), (5, None)])` or `dict([[4,None], [5, None]])` – Thy Dec 11 '22 at 04:24

1 Answers1

2

The dict built-in supports three ways of creating a dict:

class dict(**kwargs)
class dict(mapping, **kwargs)
class dict(iterable, **kwargs)

The first way is like dict(a=0, b=1). The second way is similar like dict({4:None}) used in the question. The third way is the one of interest here, the normal usage is providing an iterable of key and value pairs, e.g. like this:

>>> data = [("a", 0), ("b", 1), ("c", 2)]
>>> dict(data)
{'a': 0, 'b': 1, 'c': 2}

By using a list containing a set of two elements, you're accidentally triggering that code path. Sets are not ordered, so whether you get back {None: 4} or {4: None} here is arbitrary.

wim
  • 338,267
  • 99
  • 616
  • 750