Is there a difference between using a dict literal and a dict constructor?

前端 未结 10 2076
深忆病人
深忆病人 2020-11-28 02:26

Using PyCharm, I noticed it offers to convert a dict literal:

d = {
    \'one\': \'1\',
    \'two\': \'2\',
}

10条回答
  •  無奈伤痛
    2020-11-28 02:54

    These two approaches produce identical dictionaries, except, as you've noted, where the lexical rules of Python interfere.

    Dictionary literals are a little more obviously dictionaries, and you can create any kind of key, but you need to quote the key names. On the other hand, you can use variables for keys if you need to for some reason:

    a = "hello"
    d = {
        a: 'hi'
        }
    

    The dict() constructor gives you more flexibility because of the variety of forms of input it takes. For example, you can provide it with an iterator of pairs, and it will treat them as key/value pairs.

    I have no idea why PyCharm would offer to convert one form to the other.

提交回复
热议问题