在Python中如何正确格式化多行字典?

223 投票
9 回答
256738 浏览
提问于 2025-04-16 19:47

在Python中,我想在代码里写一个多行的字典。有几种格式可以选择。以下是我想到的一些方法:

  1. mydict = { "key1": 1,
               "key2": 2,
               "key3": 3, }
    
  2. mydict = { "key1": 1,
               "key2": 2,
               "key3": 3,
             }
    
  3. mydict = {
        "key1": 1,
        "key2": 2,
        "key3": 3,
    }
    

我知道上面这些写法在语法上都是正确的,但我想知道在Python中,写字典时有没有一种更推荐的缩进和换行风格?

注意:这不是语法问题。以上所有写法(据我所知)都是有效的Python语句,彼此之间是等价的。

9 个回答

13

因为你的键是字符串,而且我们在讨论可读性,所以我更喜欢:

mydict = dict(
    key1 = 1,
    key2 = 2,
    key3 = 3
)
36

首先,就像Steven Rumbalski说的那样,“PEP8并没有涉及这个问题”,所以这其实是个人喜好的问题。

我会使用一种和你格式3相似但不完全一样的格式。下面是我的格式,以及我这么做的原因。

my_dictionary = { # Don't think dict(...) notation has more readability
    "key1": 1, # Indent by one press of TAB (i.e. 4 spaces)
    "key2": 2, # Same indentation scale as above
    "key3": 3, # Keep this final comma, so that future addition won't show up as 2-lines change in code diff
    } # My favorite: SAME indentation AS ABOVE, to emphasize this bracket is still part of the above code block!
the_next_line_of_code() # Otherwise the previous line would look like the begin of this part of code

bad_example = {
               "foo": "bar", # Don't do this. Unnecessary indentation wastes screen space
               "hello": "world" # Don't do this. Omitting the comma is not good.
} # You see? This line visually "joins" the next line when in a glance
the_next_line_of_code()

btw_this_is_a_function_with_long_name_or_with_lots_of_parameters(
    foo='hello world',  # So I put one parameter per line
    bar=123,  # And yeah, this extra comma here is harmless too;
              # I bet not many people knew/tried this.
              # Oh did I just show you how to write
              # multiple-line inline comment here?
              # Basically, same indentation forms a natural paragraph.
    ) # Indentation here. Same idea as the long dict case.
the_next_line_of_code()

# By the way, now you see how I prefer inline comment to document the very line.
# I think this inline style is more compact.
# Otherwise you will need extra blank line to split the comment and its code from others.

some_normal_code()

# hi this function is blah blah
some_code_need_extra_explanation()

some_normal_code()
282

我用的是第3种方法。对于长列表、元组等也是一样。这种方法不需要在缩进之外再添加额外的空格。像往常一样,要保持一致。

mydict = {
    "key1": 1,
    "key2": 2,
    "key3": 3,
}

mylist = [
    (1, 'hello'),
    (2, 'world'),
]

nested = {
    a: [
        (1, 'a'),
        (2, 'b'),
    ],
    b: [
        (3, 'c'),
        (4, 'd'),
    ],
}

同样,这里是我喜欢的方式,用来包含大字符串,而不会引入任何空白(就像你使用三重引号的多行字符串时会出现的那样):

data = (
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABG"
    "l0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAEN"
    "xBRpFYmctaKCfwrBSCrRLuL3iEW6+EEUG8XvIVjYWNgJdhFjIX"
    "rz6pKtPB5e5rmq7tmxk+hqO34e1or0yXTGrj9sXGs1Ib73efh1"
    "AAAABJRU5ErkJggg=="
)

撰写回答