219

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.

Ryan C. Thompson
  • 40,856
  • 28
  • 97
  • 159

8 Answers8

278

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=="
)
FogleBird
  • 74,300
  • 25
  • 125
  • 131
  • 2
    Could you include some reference, I'm having trouble finding an authoritative source on this. (I do agree with you). – Trufa Jun 17 '11 at 16:34
  • 3
    lol, more seriously, I couldn't find an "authoritative" reference either. I'll let you know if I do! Perhaps someone should contact Guido. – FogleBird Jun 17 '11 at 19:00
  • 4
    This matches PEP 8: https://www.python.org/dev/peps/pep-0008/#indentation. There are some list examples at the bottom of the section on indentation. – Aaron Swan Jun 15 '18 at 20:52
  • Your "nested" example is invalid syntax. – data Feb 05 '20 at 14:30
  • 1
    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. – mouwsy Mar 03 '22 at 18:25
  • @data It's perfectly valid syntax, though the names `a` and `b` are undefined, maybe that's what you mean? – wjandrea Dec 22 '22 at 19:42
34

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()
RayLuo
  • 17,257
  • 6
  • 88
  • 73
  • 1
    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. – Joshua K Apr 20 '13 at 01:50
  • 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. :-) – RayLuo Apr 20 '13 at 03:32
  • 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. – Joshua K Apr 26 '13 at 13:15
  • 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. – Daniel Serodio Apr 01 '14 at 17:41
13

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

mydict = dict(
    key1 = 1,
    key2 = 2,
    key3 = 3
)
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
dugres
  • 12,613
  • 8
  • 46
  • 51
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,
    }
mouwsy
  • 1,457
  • 12
  • 20
  • 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? – Ryan C. Thompson Feb 06 '22 at 17:24
  • It says "Best practice", for reasons read the answer of RayLuo, code line 5 and 6. – mouwsy Feb 06 '22 at 20:03
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.

Max
  • 2,425
  • 6
  • 35
  • 54
-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.

Jake
  • 87
  • 1
  • 8
-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(",", "")))
-7

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

Joe
  • 269
  • 1
  • 3
  • 41
    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. – Ned Batchelder Jun 17 '11 at 19:33
  • 3
    Additionally, this answer does not address the question asked. – RKD314 Aug 19 '16 at 03:48
  • Not everyone prefer trailing commas, maybe handful of us with OCD just prefer reading a cleaner code. – Yong Feb 05 '21 at 16:03