python – 正确的字典文字布局

我看过人们喜欢格式化词典的几种不同方式,但大多数人似乎都遵循以下两种方式中的一种:

选项1)

d = {
    'key1': 'value1',
    'key2': 'value2'
    }

选项2)

d ={'key1': 'value1', 'key2': 'value2'}

在使用中都做同样的事情,但又是一个pythonic,是一个更好的格式化字典的方式,是一个简单的不正确?

我很想知道哪种格式化方式被广泛接受,并且最好在我的脚本中使用.

在我被告知之前我没有做太多的研究,我做了,它引起了更多的困惑,不同的网站,不同的人,不同的教程,经常使用不同的方式,我找不到任何说“做这样的事情,这是正确的语法“

最佳答案 在PEP 8,
indentation部分讨论了它.

Continuation lines should align wrapped elements either vertically
using Python’s implicit line joining inside parentheses, brackets and
braces, or using a hanging indent [5]

所以字典就在那里.

…brackets and braces, …

它所做的就是给出几种多线语句的方法;

# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# More indentation included to distinguish this from the rest.
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

# Hanging indents should add a level.
foo = long_function_name(
    var_one, var_two,
    var_three, var_four)

所以在你的例子中;

d ={'key1': 'value1', 'key2': 'value2'}

实际上并没有遵守PEP8 whitespace in expressions and statements,因为你错过了一个空间;它应该是(注意额外的空间.是的它是迂腐的):

d = {'key1': 'value1', 'key2': 'value2'}

至于多行版本,PEP8中的所有示例都将结束括号留在最后一行(但没有具体提到它应该去哪里).也有一些替代品,你选择的似乎只是一个偏好 – A Foolish Consistency is the Hobgoblin of Little Minds(也是PEP8).主要规则是:

When using a hanging indent the following considerations should be
applied; there should be no arguments on the first line and further
indentation should be used to clearly distinguish itself as a
continuation line.

虽然只有悬挂的凹痕和开口分隔符版本对齐.

# Aligned with opening delimiter.
d = {'key1': 'value1',
     'key2': 'value2'}

longerVariableName = {'key1': 'value1',
                      'key2': 'value2'}

# Hanging indents should add a level.
d = {
    'key1': 'value1',
    'key2': 'value2'}

longerVariableName = {
    'key1': 'value1',
    'key2': 'value2'}
点赞