在Python中格式化多行字典的正确方法是什么?

发布于 2024-11-16 02:37:41 字数 473 浏览 3 评论 0原文

在Python中,我想在我的代码中编写一个多行字典。有几种方法可以对其进行格式化。以下是我能想到的一些:

  1. mydict = { "key1": 1,
               “键2”:2,
               “键3”:3,}
    
  2. mydict = { "key1": 1,
               “键2”:2,
               “键3”:3,
             }
    
  3. mydict = {
        “键1”:1,
        “键2”:2,
        “键3”:3,
    }
    

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

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

In Python, I want to write a multi-line dict in my code. There are a couple of ways one could format it. Here are a few that I could think of:

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

I know that any of the above is syntactically correct, but I assume that there is one preferred indentation and line-break style for Python dicts. What is it?

Note: This is not an issue of syntax. All of the above are (as far as I know) valid Python statements and are equivalent to each other.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

耳钉梦 2024-11-23 02:37:41

我用#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=="
)

I use #3. Same for long lists, tuples, etc. It doesn't require adding any extra spaces beyond the indentations. As always, be consistent.

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

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

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

Similarly, here's my preferred way of including large strings without introducing any whitespace (like you'd get if you used triple-quoted multi-line strings):

data = (
    "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABG"
    "l0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAEN"
    "xBRpFYmctaKCfwrBSCrRLuL3iEW6+EEUG8XvIVjYWNgJdhFjIX"
    "rz6pKtPB5e5rmq7tmxk+hqO34e1or0yXTGrj9sXGs1Ib73efh1"
    "AAAABJRU5ErkJggg=="
)
李不 2024-11-23 02:37:41

首先,正如 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()

First of all, like Steven Rumbalski said, "PEP8 doesn't address this question", so it is a matter of personal preference.

I would use a similar but not identical format as your format 3. Here is mine, and why.

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()
笑红尘 2024-11-23 02:37:41

由于您的键是字符串,并且我们正在讨论可读性,因此我更喜欢:

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

Since your keys are strings and since we are talking about readability, I prefer :

mydict = dict(
    key1 = 1,
    key2 = 2,
    key3 = 3
)
时间海 2024-11-23 02:37:41

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

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

flake8 – a utility for enforcing style consistency in python code, which checks your code syntax and provide instructions to improve it – recommends this format (see https://www.flake8rules.com/rules/E133.html):

mydict = {
    "key1": 1,
    "key2": 2,
    "key3": 3,
    }
油饼 2024-11-23 02:37:41

通常,如果你有大的 python 对象,那么格式化它们是相当困难的。我个人更喜欢使用一些工具来实现这一点。

这是python-beautifier - www.cleancss.com/python-beautify,它可以立即转变您的数据进入可定制的风格。

Usually, if you have big python objects it's quite hard to format them. I personally prefer using some tools for that.

Here is python-beautifier - www.cleancss.com/python-beautify that instantly turns your data into customizable style.

小姐丶请自重 2024-11-23 02:37:41

如果您配置了 Black 格式化程序,它将是一行短文本字典:

{"some_key": some_value, "another_key": another_value}

当我想手动覆盖 行长配置并将字典格式设置为多行,只需在字典中添加注释即可:

{
    # some descriptive comment
    "some_key": some_value, 
    "another_key": another_value
}

黑色将使字典保持多行。

If you have configured the Black formatter, it will one-line short dictionaries:

{"some_key": some_value, "another_key": another_value}

When I want to manually override the line-length configuration and format the dictionary as multi-line, just add a comment in your dictionary:

{
    # some descriptive comment
    "some_key": some_value, 
    "another_key": another_value
}

and Black will keep the dictionary multi-line.

莫相离 2024-11-23 02:37:41

根据我在教程和其他方面的经验,第二个似乎总是首选,但这是个人偏好的选择。

From my experience with tutorials, and other things number 2 always seems preferred, but it's a personal preference choice more than anything else.

妄司 2024-11-23 02:37:41
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(",", "")))
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(",", "")))
一杆小烟枪 2024-11-23 02:37:41

通常,您不会在最终条目后包含逗号,但 Python 会为您更正它。

Generally, you would not include the comma after the final entry, but Python will correct that for you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文