What is the proper way to format a multi-line dict in Python?
Asked Answered
B

9

223

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.

Bespangle answered 17/6, 2011 at 15:35 Comment(2)
For 1 and 2: No spaces directly inside of the braces, see PEP 8.Zampino
I want to say that in pythons pprint module, it uses your first example, without spaces directly inside of the braces.Rectum
H
282

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=="
)
Holocene answered 17/6, 2011 at 15:39 Comment(6)
Could you include some reference, I'm having trouble finding an authoritative source on this. (I do agree with you).Ontario
lol, more seriously, I couldn't find an "authoritative" reference either. I'll let you know if I do! Perhaps someone should contact Guido.Holocene
This matches PEP 8: python.org/dev/peps/pep-0008/#indentation. There are some list examples at the bottom of the section on indentation.Neckar
Your "nested" example is invalid syntax.Chatman
Another advantage of this format is that you can easily comment out the first key-value pair (element), because it is on its own line.Vespiary
@Chatman It's perfectly valid syntax, though the names a and b are undefined, maybe that's what you mean?Polonaise
S
37

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()
Superadd answered 7/12, 2012 at 10:36 Comment(4)
i like the in line comment. my first programming professor (i'd already been programming for years before) insisted on inline comments, but never effectively explained why. you've now explained a practice i've used for about 20 years.Fleisig
Aha, thanks. We have similar age, experience and "mileage" in terms of programming. So if you already began that inline comment practice 20 years ago (which is impressive!), why did you still need your professor's explanation at it in presumably 10 years ago when you were in your university? Just curious. :-)Superadd
very good question :) ATARI BASIC and GWbasic practically forced it, being top-down flow line-based compilers. it's something i adopted as i read peter norton's BASIC (and later ASM code) in paper magazines. i learned Turbo Pascal in between, but i had already learned from the examples in the paper magazines and conformed to BASIC's limitations.Fleisig
PEP8 somewhat addresses it since it recommends against adding a space immediately after an opening brace, so options 1 and 2 in OP are out.Lillian
G
13

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

mydict = dict(
    key1 = 1,
    key2 = 2,
    key3 = 3
)
Gayle answered 17/6, 2011 at 17:40 Comment(1)
Prefer not using spaces when defining kwargs. c = function(a=1, b=2) is more "pythonic".Hardnett
V
2

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,
    }
Vespiary answered 6/2, 2022 at 15:43 Comment(2)
I looks like this check isn't on by default, though. It seem PEP 8 (linked from flake8) specifies either this or my style 3 from the question as acceptable alternatives. Do you have any insight as to why this one should be preferred over the other?Bespangle
It says "Best practice", for reasons read the answer of RayLuo, code line 5 and 6.Vespiary
S
1

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.

Surreptitious answered 12/10, 2016 at 16:28 Comment(0)
C
0

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.

Chenopod answered 1/4, 2024 at 0:14 Comment(0)
R
-1

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

Russia answered 17/6, 2011 at 15:39 Comment(0)
I
-2
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(",", "")))
Impassion answered 10/2, 2020 at 21:31 Comment(1)
This doesn't answer the questionAnthiathia
Z
-7

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

Zareba answered 17/6, 2011 at 19:26 Comment(3)
No! Always include the final comma, so if you add a new last element, you don't have to change the line before it. This is one of the great things about Python: practicality over purity.Galina
Additionally, this answer does not address the question asked.Sihunn
Not everyone prefer trailing commas, maybe handful of us with OCD just prefer reading a cleaner code.Emaciation

© 2022 - 2025 — McMap. All rights reserved.