파이썬에서 여러 줄로 된 dict을 형식화하는 올바른 방법은 무엇입니까? “key2”: 2,

파이썬에서는 코드에 여러 줄로 된 dict을 작성하고 싶습니다. 형식을 지정할 수있는 몇 가지 방법이 있습니다. 내가 생각할 수있는 몇 가지가 있습니다.

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

위의 구문 중 하나가 구문 적으로 정확하다는 것을 알고 있지만 Python dicts에 대해 선호되는 들여 쓰기 및 줄 바꿈 스타일이 있다고 가정합니다. 무엇입니까?

참고 : 이것은 구문 문제가 아닙니다. 위의 모든 것은 유효한 파이썬 문장이며 서로 동등합니다.



답변

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


답변

우선, 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()


답변

키는 문자열이므로 가독성에 대해 이야기하고 있기 때문에 선호합니다.

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


답변

일반적으로 큰 파이썬 객체가 있으면 포맷하기가 매우 어렵습니다. 나는 개인적으로 그것을 위해 몇 가지 도구를 사용하는 것을 선호합니다.

다음은 파이썬 아름답게은 – www.cleancss.com/python-beautify 즉시 사용자 정의 스타일로 데이터를 켜지는지.


답변

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


답변

튜토리얼에 대한 나의 경험과 다른 것들 2 번은 항상 선호되는 것처럼 보이지만 다른 무엇보다 개인적인 취향 선택입니다.


답변

일반적으로 최종 입력 후 쉼표를 포함시키지 않지만 Python 은이를 수정합니다.