Hướng dẫn pretty print list of dictionaries python - danh sách từ điển in đẹp python

Prettyformatter

Tuyên bố miễn trừ trách nhiệm: Tôi là tác giả của gói.

Để so sánh với các định dạng khác, hãy xem các định dạng khác.


Định dạng

Không giống như

{
    "id"    : "0001",
    "type"  : "donut",
    "name"  : "Cake",
    "ppu"   : 0.55,
    "batters":
        [
            {"id": "1001", "type": "Regular"},
            {"id": "1002", "type": "Chocolate"},
            {"id": "1003", "type": "Blueberry"},
            {"id": "1004", "type": "Devil's Food"},
        ],
    "topping":
        [
            {"id": "5001", "type": None},
            {"id": "5002", "type": "Glazed"},
            {"id": "5005", "type": "Sugar"},
            {"id": "5007", "type": "Powdered Sugar"},
            {"id": "5006", "type": "Chocolate with Sprinkles"},
            {"id": "5003", "type": "Chocolate"},
            {"id": "5004", "type": "Maple"},
        ],
}
2,
{
    "id"    : "0001",
    "type"  : "donut",
    "name"  : "Cake",
    "ppu"   : 0.55,
    "batters":
        [
            {"id": "1001", "type": "Regular"},
            {"id": "1002", "type": "Chocolate"},
            {"id": "1003", "type": "Blueberry"},
            {"id": "1004", "type": "Devil's Food"},
        ],
    "topping":
        [
            {"id": "5001", "type": None},
            {"id": "5002", "type": "Glazed"},
            {"id": "5005", "type": "Sugar"},
            {"id": "5007", "type": "Powdered Sugar"},
            {"id": "5006", "type": "Chocolate with Sprinkles"},
            {"id": "5003", "type": "Chocolate"},
            {"id": "5004", "type": "Maple"},
        ],
}
3 lan truyền theo chiều dọc nhiều hơn và cố gắng căn chỉnh các mục nhiều hơn.

Không giống như

{
    "id"    : "0001",
    "type"  : "donut",
    "name"  : "Cake",
    "ppu"   : 0.55,
    "batters":
        [
            {"id": "1001", "type": "Regular"},
            {"id": "1002", "type": "Chocolate"},
            {"id": "1003", "type": "Blueberry"},
            {"id": "1004", "type": "Devil's Food"},
        ],
    "topping":
        [
            {"id": "5001", "type": None},
            {"id": "5002", "type": "Glazed"},
            {"id": "5005", "type": "Sugar"},
            {"id": "5007", "type": "Powdered Sugar"},
            {"id": "5006", "type": "Chocolate with Sprinkles"},
            {"id": "5003", "type": "Chocolate"},
            {"id": "5004", "type": "Maple"},
        ],
}
4,
{
    "id"    : "0001",
    "type"  : "donut",
    "name"  : "Cake",
    "ppu"   : 0.55,
    "batters":
        [
            {"id": "1001", "type": "Regular"},
            {"id": "1002", "type": "Chocolate"},
            {"id": "1003", "type": "Blueberry"},
            {"id": "1004", "type": "Devil's Food"},
        ],
    "topping":
        [
            {"id": "5001", "type": None},
            {"id": "5002", "type": "Glazed"},
            {"id": "5005", "type": "Sugar"},
            {"id": "5007", "type": "Powdered Sugar"},
            {"id": "5006", "type": "Chocolate with Sprinkles"},
            {"id": "5003", "type": "Chocolate"},
            {"id": "5004", "type": "Maple"},
        ],
}
3 thường nhỏ gọn hơn và cố gắng sắp xếp các giá trị từ điển bất cứ nơi nào hợp lý.

from prettyformatter import pprint

batters = [
    {"id": "1001", "type": "Regular"},
    {"id": "1002", "type": "Chocolate"},
    {"id": "1003", "type": "Blueberry"},
    {"id": "1004", "type": "Devil's Food"},
]

toppings = [
    {"id": "5001", "type": None},
    {"id": "5002", "type": "Glazed"},
    {"id": "5005", "type": "Sugar"},
    {"id": "5007", "type": "Powdered Sugar"},
    {"id": "5006", "type": "Chocolate with Sprinkles"},
    {"id": "5003", "type": "Chocolate"},
    {"id": "5004", "type": "Maple"},
]

data = {"id": "0001", "type": "donut", "name": "Cake", "ppu": 0.55, "batters": batters, "topping": toppings}

pprint(data)

Output:

{
    "id"    : "0001",
    "type"  : "donut",
    "name"  : "Cake",
    "ppu"   : 0.55,
    "batters":
        [
            {"id": "1001", "type": "Regular"},
            {"id": "1002", "type": "Chocolate"},
            {"id": "1003", "type": "Blueberry"},
            {"id": "1004", "type": "Devil's Food"},
        ],
    "topping":
        [
            {"id": "5001", "type": None},
            {"id": "5002", "type": "Glazed"},
            {"id": "5005", "type": "Sugar"},
            {"id": "5007", "type": "Powdered Sugar"},
            {"id": "5006", "type": "Chocolate with Sprinkles"},
            {"id": "5003", "type": "Chocolate"},
            {"id": "5004", "type": "Maple"},
        ],
}

Đặc trưng

Xem ở đây để biết tài liệu đầy đủ.

Json

Không giống như

{
    "id"    : "0001",
    "type"  : "donut",
    "name"  : "Cake",
    "ppu"   : 0.55,
    "batters":
        [
            {"id": "1001", "type": "Regular"},
            {"id": "1002", "type": "Chocolate"},
            {"id": "1003", "type": "Blueberry"},
            {"id": "1004", "type": "Devil's Food"},
        ],
    "topping":
        [
            {"id": "5001", "type": None},
            {"id": "5002", "type": "Glazed"},
            {"id": "5005", "type": "Sugar"},
            {"id": "5007", "type": "Powdered Sugar"},
            {"id": "5006", "type": "Chocolate with Sprinkles"},
            {"id": "5003", "type": "Chocolate"},
            {"id": "5004", "type": "Maple"},
        ],
}
2,
{
    "id"    : "0001",
    "type"  : "donut",
    "name"  : "Cake",
    "ppu"   : 0.55,
    "batters":
        [
            {"id": "1001", "type": "Regular"},
            {"id": "1002", "type": "Chocolate"},
            {"id": "1003", "type": "Blueberry"},
            {"id": "1004", "type": "Devil's Food"},
        ],
    "topping":
        [
            {"id": "5001", "type": None},
            {"id": "5002", "type": "Glazed"},
            {"id": "5005", "type": "Sugar"},
            {"id": "5007", "type": "Powdered Sugar"},
            {"id": "5006", "type": "Chocolate with Sprinkles"},
            {"id": "5003", "type": "Chocolate"},
            {"id": "5004", "type": "Maple"},
        ],
}
3 hỗ trợ chuyển đổi JSON thông qua đối số
{
    "id"    : "0001",
    "type"  : "donut",
    "name"  : "Cake",
    "ppu"   : 0.55,
    "batters":
        [
            {"id": "1001", "type": "Regular"},
            {"id": "1002", "type": "Chocolate"},
            {"id": "1003", "type": "Blueberry"},
            {"id": "1004", "type": "Devil's Food"},
        ],
    "topping":
        [
            {"id": "5001", "type": None},
            {"id": "5002", "type": "Glazed"},
            {"id": "5005", "type": "Sugar"},
            {"id": "5007", "type": "Powdered Sugar"},
            {"id": "5006", "type": "Chocolate with Sprinkles"},
            {"id": "5003", "type": "Chocolate"},
            {"id": "5004", "type": "Maple"},
        ],
}
8. Điều này bao gồm thay đổi
{
    "id"    : "0001",
    "type"  : "donut",
    "name"  : "Cake",
    "ppu"   : 0.55,
    "batters":
        [
            {"id": "1001", "type": "Regular"},
            {"id": "1002", "type": "Chocolate"},
            {"id": "1003", "type": "Blueberry"},
            {"id": "1004", "type": "Devil's Food"},
        ],
    "topping":
        [
            {"id": "5001", "type": None},
            {"id": "5002", "type": "Glazed"},
            {"id": "5005", "type": "Sugar"},
            {"id": "5007", "type": "Powdered Sugar"},
            {"id": "5006", "type": "Chocolate with Sprinkles"},
            {"id": "5003", "type": "Chocolate"},
            {"id": "5004", "type": "Maple"},
        ],
}
9 thành
from dataclasses import dataclass

from prettyformatter import PrettyDataclass, pprint


@dataclass(unsafe_hash=True)
class Point(PrettyDataclass):
    x: int
    y: int


pprint((Point(1, 2), Point(3, 4)), json=True)
0,
from dataclasses import dataclass

from prettyformatter import PrettyDataclass, pprint


@dataclass(unsafe_hash=True)
class Point(PrettyDataclass):
    x: int
    y: int


pprint((Point(1, 2), Point(3, 4)), json=True)
1 thành
from dataclasses import dataclass

from prettyformatter import PrettyDataclass, pprint


@dataclass(unsafe_hash=True)
class Point(PrettyDataclass):
    x: int
    y: int


pprint((Point(1, 2), Point(3, 4)), json=True)
2,
from dataclasses import dataclass

from prettyformatter import PrettyDataclass, pprint


@dataclass(unsafe_hash=True)
class Point(PrettyDataclass):
    x: int
    y: int


pprint((Point(1, 2), Point(3, 4)), json=True)
3 thành
from dataclasses import dataclass

from prettyformatter import PrettyDataclass, pprint


@dataclass(unsafe_hash=True)
class Point(PrettyDataclass):
    x: int
    y: int


pprint((Point(1, 2), Point(3, 4)), json=True)
4 và sử dụng đúng các trích dẫn.

Không giống như

{
    "id"    : "0001",
    "type"  : "donut",
    "name"  : "Cake",
    "ppu"   : 0.55,
    "batters":
        [
            {"id": "1001", "type": "Regular"},
            {"id": "1002", "type": "Chocolate"},
            {"id": "1003", "type": "Blueberry"},
            {"id": "1004", "type": "Devil's Food"},
        ],
    "topping":
        [
            {"id": "5001", "type": None},
            {"id": "5002", "type": "Glazed"},
            {"id": "5005", "type": "Sugar"},
            {"id": "5007", "type": "Powdered Sugar"},
            {"id": "5006", "type": "Chocolate with Sprinkles"},
            {"id": "5003", "type": "Chocolate"},
            {"id": "5004", "type": "Maple"},
        ],
}
4,
{
    "id"    : "0001",
    "type"  : "donut",
    "name"  : "Cake",
    "ppu"   : 0.55,
    "batters":
        [
            {"id": "1001", "type": "Regular"},
            {"id": "1002", "type": "Chocolate"},
            {"id": "1003", "type": "Blueberry"},
            {"id": "1004", "type": "Devil's Food"},
        ],
    "topping":
        [
            {"id": "5001", "type": None},
            {"id": "5002", "type": "Glazed"},
            {"id": "5005", "type": "Sugar"},
            {"id": "5007", "type": "Powdered Sugar"},
            {"id": "5006", "type": "Chocolate with Sprinkles"},
            {"id": "5003", "type": "Chocolate"},
            {"id": "5004", "type": "Maple"},
        ],
}
3 hỗ trợ sự ép buộc của JSON với nhiều loại dữ liệu hơn. Điều này bao gồm thay đổi bất kỳ
from dataclasses import dataclass

from prettyformatter import PrettyDataclass, pprint


@dataclass(unsafe_hash=True)
class Point(PrettyDataclass):
    x: int
    y: int


pprint((Point(1, 2), Point(3, 4)), json=True)
7 hoặc
from dataclasses import dataclass

from prettyformatter import PrettyDataclass, pprint


@dataclass(unsafe_hash=True)
class Point(PrettyDataclass):
    x: int
    y: int


pprint((Point(1, 2), Point(3, 4)), json=True)
8 thành
from dataclasses import dataclass

from prettyformatter import PrettyDataclass, pprint


@dataclass(unsafe_hash=True)
class Point(PrettyDataclass):
    x: int
    y: int


pprint((Point(1, 2), Point(3, 4)), json=True)
9 và bất kỳ
[{"x": 1, "y": 2}, {"x": 3, "y": 4}]
0 nào thành
[{"x": 1, "y": 2}, {"x": 3, "y": 4}]
1.

from dataclasses import dataclass

from prettyformatter import PrettyDataclass, pprint


@dataclass(unsafe_hash=True)
class Point(PrettyDataclass):
    x: int
    y: int


pprint((Point(1, 2), Point(3, 4)), json=True)

Output:

[{"x": 1, "y": 2}, {"x": 3, "y": 4}]

Tùy chỉnh

Không giống như

{
    "id"    : "0001",
    "type"  : "donut",
    "name"  : "Cake",
    "ppu"   : 0.55,
    "batters":
        [
            {"id": "1001", "type": "Regular"},
            {"id": "1002", "type": "Chocolate"},
            {"id": "1003", "type": "Blueberry"},
            {"id": "1004", "type": "Devil's Food"},
        ],
    "topping":
        [
            {"id": "5001", "type": None},
            {"id": "5002", "type": "Glazed"},
            {"id": "5005", "type": "Sugar"},
            {"id": "5007", "type": "Powdered Sugar"},
            {"id": "5006", "type": "Chocolate with Sprinkles"},
            {"id": "5003", "type": "Chocolate"},
            {"id": "5004", "type": "Maple"},
        ],
}
2 hoặc
{
    "id"    : "0001",
    "type"  : "donut",
    "name"  : "Cake",
    "ppu"   : 0.55,
    "batters":
        [
            {"id": "1001", "type": "Regular"},
            {"id": "1002", "type": "Chocolate"},
            {"id": "1003", "type": "Blueberry"},
            {"id": "1004", "type": "Devil's Food"},
        ],
    "topping":
        [
            {"id": "5001", "type": None},
            {"id": "5002", "type": "Glazed"},
            {"id": "5005", "type": "Sugar"},
            {"id": "5007", "type": "Powdered Sugar"},
            {"id": "5006", "type": "Chocolate with Sprinkles"},
            {"id": "5003", "type": "Chocolate"},
            {"id": "5004", "type": "Maple"},
        ],
}
4,
{
    "id"    : "0001",
    "type"  : "donut",
    "name"  : "Cake",
    "ppu"   : 0.55,
    "batters":
        [
            {"id": "1001", "type": "Regular"},
            {"id": "1002", "type": "Chocolate"},
            {"id": "1003", "type": "Blueberry"},
            {"id": "1004", "type": "Devil's Food"},
        ],
    "topping":
        [
            {"id": "5001", "type": None},
            {"id": "5002", "type": "Glazed"},
            {"id": "5005", "type": "Sugar"},
            {"id": "5007", "type": "Powdered Sugar"},
            {"id": "5006", "type": "Chocolate with Sprinkles"},
            {"id": "5003", "type": "Chocolate"},
            {"id": "5004", "type": "Maple"},
        ],
}
3 hỗ trợ tùy chỉnh dễ dàng với các loại bổ sung.

Việc triển khai các phương thức

[{"x": 1, "y": 2}, {"x": 3, "y": 4}]
5 và/hoặc
[{"x": 1, "y": 2}, {"x": 3, "y": 4}]
6 cho lớp con
[{"x": 1, "y": 2}, {"x": 3, "y": 4}]
7 cho phép một người dễ dàng tùy chỉnh các lớp dưới dạng
[{"x": 1, "y": 2}, {"x": 3, "y": 4}]
8.

from prettyformatter import PrettyClass


class Dog(PrettyClass):

    def __init__(self, name, **kwargs):
        self.name = name

    def __pkwargs__(self):
        return {"name": self.name}


print(Dog("Fido"))
"""
Dog(name="Fido")
"""

print(Dog("Fido"), json=True)
"""
{"name": "Fido"}
"""

Việc thực hiện phương thức

[{"x": 1, "y": 2}, {"x": 3, "y": 4}]
9 cho phép các triển khai cụ thể hơn của hàm
from prettyformatter import PrettyClass


class Dog(PrettyClass):

    def __init__(self, name, **kwargs):
        self.name = name

    def __pkwargs__(self):
        return {"name": self.name}


print(Dog("Fido"))
"""
Dog(name="Fido")
"""

print(Dog("Fido"), json=True)
"""
{"name": "Fido"}
"""
0.

Việc thực hiện chức năng

from prettyformatter import PrettyClass


class Dog(PrettyClass):

    def __init__(self, name, **kwargs):
        self.name = name

    def __pkwargs__(self):
        return {"name": self.name}


print(Dog("Fido"))
"""
Dog(name="Fido")
"""

print(Dog("Fido"), json=True)
"""
{"name": "Fido"}
"""
1 cũng cho phép các lớp tùy chỉnh đã tồn tại giống như cách thực hiện
[{"x": 1, "y": 2}, {"x": 3, "y": 4}]
9.

import numpy as np
from prettyformatter import pprint, register

@register(np.ndarray)
def pformat_ndarray(obj, specifier, depth, indent, shorten, json):
    if json:
        return pformat(obj.tolist(), specifier, depth, indent, shorten, json)
    with np.printoptions(formatter=dict(all=lambda x: format(x, specifier))):
        return repr(obj).replace("\n", "\n" + " " * depth)

pprint(dict.fromkeys("ABC", np.arange(9).reshape(3, 3)))

Output:

{
    "A":
        array([[0, 1, 2],
               [3, 4, 5],
               [6, 7, 8]]),
    "B":
        array([[0, 1, 2],
               [3, 4, 5],
               [6, 7, 8]]),
    "C":
        array([[0, 1, 2],
               [3, 4, 5],
               [6, 7, 8]]),
}

Trong Tutoria này, bạn sẽ học cách sử dụng Python để in đẹp Dict (Từ điển). Bạn sẽ học cách sử dụng thư viện & nbsp; ____ 43 & nbsp; cũng như thư viện & nbsp; Bạn cũng sẽ học cách in từ điển đẹp mắt trong Python. Cuối cùng, bạn sẽ học cách lưu một Dict được in đẹp trong Python vào một tập tin.

Từ điển là một thành phần chính của việc làm việc với dữ liệu trong Python, bao gồm cả dữ liệu được tải từ Internet. Nhiều API trả về dữ liệu ở định dạng JSON, rất giống với định dạng của từ điển Python. Từ điển cung cấp những cách cực kỳ hữu ích để bạn có thể lưu trữ và truy xuất dữ liệu. Tuy nhiên, chúng có thể là một chút khó khăn để đọc. Bởi vì điều này, nó thường hữu ích để có thể in ra từ điển của bạn ở định dạng có thể đọc được hơn. Không cần phải quảng cáo thêm nữa, hãy để Lừa xem những gì bạn sẽ học!

Câu trả lời nhanh: Sử dụng thư viện JSON: Use the json library

Hướng dẫn pretty print list of dictionaries python - danh sách từ điển in đẹp python

  • Từ điển Python là gì?
  • In đẹp một dict in python với pprint
  • In Pretty a dict in python with json
  • In đẹp một từ điển lồng nhau trong Python
  • Lưu một từ điển được in đẹp vào một tệp
  • Sự kết luận

Từ điển Python là gì?

In đẹp một dict in python với pprint

Hãy cùng xem một từ điển trông như thế nào trong Python:

sample_dict = {
    'age': 31,
    'gender': 'male',
    'books': ['Harry Potter', 'Lord of the Rings']
}

Chúng ta có thể lấy một giá trị nếu chúng ta biết khóa từ điển. Ví dụ: nếu chúng tôi muốn truy xuất giá trị cho & nbsp; ____ 46, chúng tôi có thể viết đơn giản: & nbsp; ________ 47, sẽ trả về & nbsp; ________ 48.

Bây giờ chúng ta có một sự hiểu biết về từ điển Python là gì, hãy để Lôi xem cách in chúng.

Cần kiểm tra xem một chìa khóa có tồn tại trong từ điển Python không? Kiểm tra hướng dẫn này, trong đó dạy cho bạn năm cách khác nhau để xem nếu một chìa khóa có tồn tại trong từ điển Python, bao gồm cả cách trả về giá trị mặc định. Check out this tutorial, which teaches you five different ways of seeing if a key exists in a Python dictionary, including how to return a default value.

In đẹp một dict in python với pprint

Python đi kèm với một thư viện tích hợp có tên & nbsp; ____ 43, viết tắt của bản in đẹp. Sử dụng thư viện này, chúng ta có thể in ra các cấu trúc dữ liệu được định dạng độc đáo hơn, bao gồm cả từ điển.

Thư viện & nbsp; ____ 43 & nbsp; cho phép chúng tôi chỉ định một số tham số khác nhau, bao gồm các thông số sau:

  1. import numpy as np
    from prettyformatter import pprint, register
    
    @register(np.ndarray)
    def pformat_ndarray(obj, specifier, depth, indent, shorten, json):
        if json:
            return pformat(obj.tolist(), specifier, depth, indent, shorten, json)
        with np.printoptions(formatter=dict(all=lambda x: format(x, specifier))):
            return repr(obj).replace("\n", "\n" + " " * depth)
    
    pprint(dict.fromkeys("ABC", np.arange(9).reshape(3, 3)))
    
    1: Số lượng không gian để thụt lên mỗi dòng, trong đó giá trị mặc định là & nbsp; ________ 52
  2. import numpy as np
    from prettyformatter import pprint, register
    
    @register(np.ndarray)
    def pformat_ndarray(obj, specifier, depth, indent, shorten, json):
        if json:
            return pformat(obj.tolist(), specifier, depth, indent, shorten, json)
        with np.printoptions(formatter=dict(all=lambda x: format(x, specifier))):
            return repr(obj).replace("\n", "\n" + " " * depth)
    
    pprint(dict.fromkeys("ABC", np.arange(9).reshape(3, 3)))
    
    3: Các caharacters tối đa được phép trên một dòng, trong đó mặc định là & nbsp; ________ 19 & nbsp; (có nghĩa là tối đa)
  3. import numpy as np
    from prettyformatter import pprint, register
    
    @register(np.ndarray)
    def pformat_ndarray(obj, specifier, depth, indent, shorten, json):
        if json:
            return pformat(obj.tolist(), specifier, depth, indent, shorten, json)
        with np.printoptions(formatter=dict(all=lambda x: format(x, specifier))):
            return repr(obj).replace("\n", "\n" + " " * depth)
    
    pprint(dict.fromkeys("ABC", np.arange(9).reshape(3, 3)))
    
    5: Số lượng cấp độ để hiển thị trong khi sử dụng các loại dữ liệu lồng nhau, trong đó mặc định là & nbsp;
  4. import numpy as np
    from prettyformatter import pprint, register
    
    @register(np.ndarray)
    def pformat_ndarray(obj, specifier, depth, indent, shorten, json):
        if json:
            return pformat(obj.tolist(), specifier, depth, indent, shorten, json)
        with np.printoptions(formatter=dict(all=lambda x: format(x, specifier))):
            return repr(obj).replace("\n", "\n" + " " * depth)
    
    pprint(dict.fromkeys("ABC", np.arange(9).reshape(3, 3)))
    
    7: Được sử dụng để chỉ định luồng đầu ra và có thể được sử dụng để lưu vào tệp
  5. import numpy as np
    from prettyformatter import pprint, register
    
    @register(np.ndarray)
    def pformat_ndarray(obj, specifier, depth, indent, shorten, json):
        if json:
            return pformat(obj.tolist(), specifier, depth, indent, shorten, json)
        with np.printoptions(formatter=dict(all=lambda x: format(x, specifier))):
            return repr(obj).replace("\n", "\n" + " " * depth)
    
    pprint(dict.fromkeys("ABC", np.arange(9).reshape(3, 3)))
    
    8: Nếu được đặt thành & nbsp; ________ 21, các giá trị sẽ được in trên các dòng đơn, theo chiều rộng nhất định
  6. {
        "A":
            array([[0, 1, 2],
                   [3, 4, 5],
                   [6, 7, 8]]),
        "B":
            array([[0, 1, 2],
                   [3, 4, 5],
                   [6, 7, 8]]),
        "C":
            array([[0, 1, 2],
                   [3, 4, 5],
                   [6, 7, 8]]),
    }
    
    0: Nếu & nbsp; ________ 21, nó in các cặp giá trị khóa theo thứ tự bảng chữ cái của các phím. Mặc định là & nbsp; ________ 21

Hãy để tải một từ điển và xem cách chúng ta có thể in nó bằng Python:

# Pretty Print a Dictionary using pprint
import pprint

sample_dict = {'name': 'Nik', 'age': 31, 'gender': 'male', 'books': ['Harry Potter', 'Lord of the Rings']}
pprint.pprint(sample_dict)

# Returns:
# {'name': 'Nik',
#  'age': 31,
#  'books': ['Harry Potter', 'Lord of the Rings'],
#  'gender': 'male'}

Trong phần tiếp theo, bạn sẽ học cách sử dụng thư viện JSON để in đẹp Dict Python.

Bạn muốn tìm hiểu thêm về toàn bộ danh sách Python? Kiểm tra hướng dẫn chuyên sâu này bao gồm mọi thứ bạn cần biết, với các ví dụ thực hành. Thêm một người học trực quan, hãy xem hướng dẫn YouTube của tôi ở đây. Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here.

In Pretty a dict in python with json

Như đã đề cập trước đó, từ điển Python mang rất nhiều đặc điểm tương tự với các đối tượng JSON. Vì điều này, chúng ta có thể sử dụng thư viện JSON để trả về chuỗi JSON được định dạng.

Được tích hợp vào thư viện & nbsp; Chúng ta hãy xem xét các chức năng & nbsp;

  1. ________ 66 & nbsp; sắp xếp các khóa từ điển và mặc định là & nbsp; ________ 23
  2. import numpy as np
    from prettyformatter import pprint, register
    
    @register(np.ndarray)
    def pformat_ndarray(obj, specifier, depth, indent, shorten, json):
        if json:
            return pformat(obj.tolist(), specifier, depth, indent, shorten, json)
        with np.printoptions(formatter=dict(all=lambda x: format(x, specifier))):
            return repr(obj).replace("\n", "\n" + " " * depth)
    
    pprint(dict.fromkeys("ABC", np.arange(9).reshape(3, 3)))
    
    1: cho phép Python biết có bao nhiêu không gian để thụt vào

Hãy để sử dụng cùng một từ điển như trên và in đẹp bằng cách sử dụng Python, & nbsp; ________ 44 & nbsp; thư viện:

# Pretty Print a Dictionary using json
import json

sample_dict = {'Nik':{'age': 31, 'gender': 'male', 'books': ['Harry Potter', 'Lord of the Rings']}, 'Joe': {'age': 40, 'gender': 'male', 'books':['Lord of the Flies']}}
pretty = json.dumps(sample_dict, indent=4)

print(pretty)

# Returns:
# {
#     "name": "Nik",
#     "age": 31,
#     "gender": "male",
#     "books": [
#         "Harry Potter",
#         "Lord of the Rings"
#     ]
# }

Chúng ta có thể thấy ở đây rằng điều này trả về một từ điển in rất giống nhau, với sự khác biệt chính: danh sách cũng được in trên các dòng riêng biệt, giúp đọc dễ dàng hơn. Điều này, tất nhiên, là một cách đẹp hơn nhiều để in từ điển của bạn.

Trong phần tiếp theo, bạn sẽ học cách in đẹp từ điển lồng nhau bằng Python.

Bạn muốn tìm hiểu làm thế nào để in đẹp một tệp JSON bằng Python? Tìm hiểu ba phương pháp khác nhau để thực hiện điều này bằng cách sử dụng hướng dẫn chuyên sâu này ở đây. Learn three different methods to accomplish this using this in-depth tutorial here.

Trong nhiều trường hợp, từ điển của bạn sẽ phức tạp. Bạn thậm chí có thể gặp các từ điển có chứa các từ điển khác. Ví dụ, bạn có thể có một từ điển chứa thông tin về những người khác nhau. Mỗi khóa của từ điển cấp cao nhất sẽ đại diện cho một người tên và giá trị sẽ là một từ điển khác nhau sẽ mô tả các thuộc tính chính của một người.

Do sự phức tạp của từ điển bạn có thể gặp phải, để hiểu rõ hơn về cấu trúc của chúng, bạn có thể muốn in chúng ra một cách mô tả một cách thích hợp hơn về cấu trúc của chúng.

Sử dụng thư viện & nbsp; ____ 44 & nbsp; điều này thực sự rất dễ dàng! Nó thực sự hoạt động theo cách tương tự như in một từ điển bình thường. Hãy để một cái nhìn:

{
    "id"    : "0001",
    "type"  : "donut",
    "name"  : "Cake",
    "ppu"   : 0.55,
    "batters":
        [
            {"id": "1001", "type": "Regular"},
            {"id": "1002", "type": "Chocolate"},
            {"id": "1003", "type": "Blueberry"},
            {"id": "1004", "type": "Devil's Food"},
        ],
    "topping":
        [
            {"id": "5001", "type": None},
            {"id": "5002", "type": "Glazed"},
            {"id": "5005", "type": "Sugar"},
            {"id": "5007", "type": "Powdered Sugar"},
            {"id": "5006", "type": "Chocolate with Sprinkles"},
            {"id": "5003", "type": "Chocolate"},
            {"id": "5004", "type": "Maple"},
        ],
}
0

Trong phần tiếp theo, bạn sẽ học cách lưu một từ điển được in đẹp vào một tệp.

Kiểm tra một số hướng dẫn Python khác trên DataGy.io, bao gồm hướng dẫn đầy đủ của chúng tôi để tạo kiểu gấu trúc và tổng quan toàn diện của chúng tôi về các bảng trục trong gấu trúc!

Lưu một từ điển được in đẹp vào một tệp

Cuối cùng, hãy để Lừa xem cách lưu một dict được in đẹp cho một tập tin. Chúng tôi có thể sử dụng thư viện & nbsp; ____ 43 & nbsp; để thực hiện điều này, với sự trợ giúp của người quản lý bối cảnh.

Hãy để xem cách thực hiện điều này bằng cách sử dụng Python:

{
    "id"    : "0001",
    "type"  : "donut",
    "name"  : "Cake",
    "ppu"   : 0.55,
    "batters":
        [
            {"id": "1001", "type": "Regular"},
            {"id": "1002", "type": "Chocolate"},
            {"id": "1003", "type": "Blueberry"},
            {"id": "1004", "type": "Devil's Food"},
        ],
    "topping":
        [
            {"id": "5001", "type": None},
            {"id": "5002", "type": "Glazed"},
            {"id": "5005", "type": "Sugar"},
            {"id": "5007", "type": "Powdered Sugar"},
            {"id": "5006", "type": "Chocolate with Sprinkles"},
            {"id": "5003", "type": "Chocolate"},
            {"id": "5004", "type": "Maple"},
        ],
}
1

Chúng tôi sử dụng trình quản lý bối cảnh bằng & nbsp; ____ 72 & nbsp; hàm để liên kết đến một tệp cụ thể nơi chúng tôi muốn lưu từ điển của chúng tôi và sau đó sử dụng & nbsp; ____ 73 & nbsp; tham số để nói rằng chúng tôi muốn ghi vào tệp. Sau đó, chúng tôi chuyển từ điển và file_name này vào chức năng & nbsp; ________ 74 & nbsp; để lưu nó vào một tệp.

Bạn muốn tìm hiểu thêm về Python for-loops?Kiểm tra hướng dẫn chuyên sâu của tôi đưa người dùng từ người mới bắt đầu đến nâng cao cho người dùng!Bạn muốn xem một video thay thế?Kiểm tra hướng dẫn YouTube của tôi ở đây. Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.

Sự kết luận

Trong bài đăng này, bạn đã học được cách sử dụng Python để in đẹp.Bạn đã học cách thực hiện việc này bằng cách sử dụng & nbsp; ____ 43 & nbsp; và & nbsp; ________ 44 & nbsp; thư viện và học các cách thức mà hai cách tiếp cận này khác nhau.Bạn cũng đã học được cách in từ điển đẹp mắt bằng Python cũng như cách lưu từ điển được in đẹp vào một tệp.

Để tìm hiểu thêm về & nbsp; ____ 43 & nbsp; thư viện, hãy xem tài liệu chính thức ở đây.