简体   繁体   English

为什么 dict({4:None}) 返回 {4: None} 而 dict([{4,None}]) 在 Python 中返回 {None: 4} 3.11

[英]why does dict({4:None}) returns {4: None} but dict([{4,None}]) returns {None: 4} in Python 3.11

I was fiddling with dict() and found out that when I do我在摆弄 dict() 并发现当我这样做时

>>> dict({4:None}) it returns {4: None} which is expected but, >>> dict({4:None})它返回预期的{4: None}但是,

when I try converting a list containing a nested set [{4,None}]当我尝试转换包含嵌套集[{4,None}]的列表时

>>> dict([{4,None}]) returns {None: 4} which genuinely unexpected. >>> dict([{4,None}])返回真正出乎意料的{None: 4}

Then I checked that it only happens with few integers.然后我检查它只发生在几个整数上。 That is crazy.这很疯狂。

eg dict([{5,None}]) returns {None: 5}例如dict([{5,None}])返回{None: 5}

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

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

although虽然

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

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

Can anyone answer this?谁能回答这个问题? I am using Python 3.11我正在使用 Python 3.11

The dict built-in supports three ways of creating a dict:内置的dict支持三种创建字典的方式:

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

The first way is like dict(a=0, b=1) .第一种方式类似于dict(a=0, b=1) The second way is similar like dict({4:None}) used in the question.第二种方式类似于问题中使用的dict({4:None}) The third way is the one of interest here, the normal usage is providing an iterable of key and value pairs, eg 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.集合没有顺序,所以你在这里返回{None: 4}{4: None}是任意的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM