在Python中,我想在我的代码中编写一个多行字典。有几种格式。以下是我能想到的一些建议:

Mydict = {"key1": 1, “key2”:2 "key3": 3,} Mydict = {"key1": 1, “key2”:2 “key3”:3, } Mydict = { “key1”:1、 “key2”:2 “key3”:3, }

我知道上面的任何一个在语法上都是正确的,但我假设Python字典有一种首选的缩进和换行样式。是什么?

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


当前回答

首先,就像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()

其他回答

根据我在教程和其他方面的经验,第二种选择似乎更受欢迎,但这只是个人偏好的选择。

通常,你不会在最后一项后面加上逗号,但Python会为你纠正这一点。

通常,如果你有大的python对象,很难格式化它们。我个人更喜欢使用一些工具。

这里是python-beautifier - www.cleancss.com/python-beautify,可以立即将您的数据转换为可定制的样式。

flake8 -一个用于在python代码中强制风格一致性的实用程序,它检查代码语法并提供改进指令-推荐这种格式(参见https://www.flake8rules.com/rules/E133.html):)

mydict = {
    "key1": 1,
    "key2": 2,
    "key3": 3,
    }
dict(rank = int(lst[0]),
                grade = str(lst[1]),
                channel=str(lst[2])),
                videos = float(lst[3].replace(",", " ")),
                subscribers = float(lst[4].replace(",", "")),
                views = float(lst[5].replace(",", "")))