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

前端 未结 10 2039
深忆病人
深忆病人 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:51

    From python 2.7 tutorial:

    A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.

    tel = {'jack': 4098, 'sape': 4139}
    data = {k:v for k,v in zip(xrange(10), xrange(10,20))}
    

    While:

    The dict() constructor builds dictionaries directly from lists of key-value pairs stored as tuples. When the pairs form a pattern, list comprehensions can compactly specify the key-value list.

    tel = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) {'sape': 4139, 'jack': 4098, 'guido': 4127}
    data = dict((k,v) for k,v in zip(xrange(10), xrange(10,20)))
    

    When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:

    dict(sape=4139, guido=4127, jack=4098)
    >>>  {'sape': 4139, 'jack':4098, 'guido': 4127}
    

    So both {} and dict() produce dictionary but provide a bit different ways of dictionary data initialization.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-28 02:54

    I find the dict literal d = {'one': '1'} to be much more readable, your defining data, rather than assigning things values and sending them to the dict() constructor.

    On the other hand i have seen people mistype the dict literal as d = {'one', '1'} which in modern python 2.7+ will create a set.

    Despite this i still prefer to all-ways use the set literal because i think its more readable, personal preference i suppose.

    0 讨论(0)
  • 2020-11-28 02:57

    One big difference with python 3.4 + pycharm is that the dict() constructor produces a "syntax error" message if the number of keys exceeds 256.

    I prefer using the dict literal now.

    0 讨论(0)
提交回复
热议问题