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

后端 未结 7 1494
天命终不由人
天命终不由人 2020-11-29 16:19

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. mydic         
    
    
            
7条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 16:36

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

提交回复
热议问题