[python] What is the proper way to format a multi-line dict in 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.

This question is related to python indentation code-formatting multiline

The answer is


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


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.


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

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

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()

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


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(",", "")))

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to indentation

How to indent/format a selection of code in Visual Studio Code with Ctrl + Shift + F Python IndentationError unindent does not match any outer indentation level How to change indentation mode in Atom? How to set HTML Auto Indent format on Sublime Text 3? "Expected an indented block" error? Indent starting from the second line of a paragraph with CSS Indentation Error in Python How to fix/convert space indentation in Sublime Text? How to make the tab character 4 spaces instead of 8 spaces in nano? IndentationError: unexpected unindent WHY?

Examples related to code-formatting

How do you format code on save in VS Code How do you format code in Visual Studio Code (VSCode) JavaScript Chart.js - Custom data formatting to display on tooltip Is there a command for formatting HTML in the Atom editor? How to auto-indent code in the Atom editor? Code formatting shortcuts in Android Studio for Operation Systems How to auto-format code in Eclipse? How to format code in Xcode? What is the proper way to format a multi-line dict in Python? How do I format XML in Notepad++?

Examples related to multiline

Way to create multiline comments in Bash? How to get multiline input from user R: "Unary operator error" from multiline ggplot2 command Can a JSON value contain a multiline string PHP multiline string with PHP Pythonic way to create a long multi-line string How do I create a multiline Python string with inline variables? How do you write multiline strings in Go? Multiline TextView in Android? What is the proper way to format a multi-line dict in Python?