在Python中格式化多行字典的正确方法是什么? [英] What is the proper way to format a multi-line dict in Python?

查看:888
本文介绍了在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:

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

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

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

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

    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?

    注意:这不是语法问题.就我所知,以上所有都是有效的Python语句,并且彼此等效.

    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.

    推荐答案

    我使用#3.与长列表,元组等相同.不需要在缩进之外添加任何额外的空格.一如既往,保持一致.

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

    这篇关于在Python中格式化多行字典的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆