gpt4 book ai didi

python - 如何将 Python 字典树化?

转载 作者:行者123 更新时间:2023-12-01 01:14:04 25 4
gpt4 key购买 nike

我正在构建一个电报机器人,并且想要转换 json 响应,例如下面我将其转换为字典的响应:

{
"message_id": 445793,
"from": {
"id": 106596774,
"is_bot": false,
"first_name": "Komron",
"last_name": "Aripov",
"username": "tgcode",
"language_code": "en"
},
"chat": {
"id": 106596774,
"first_name": "Komron",
"last_name": "Aripov",
"username": "tgcode",
"type": "private"
},
"date": 1549380586,
"text": "ayye"
}

变成一棵整齐的小树,比如这样:

Message
├ message_id: 445793
├ from
┊ ├ id: 106596774
┊ ├ is_bot: false
┊ ├ first_name: Komron
┊ ├ last_name: Aripov
┊ ├ username: tgcode
┊ └ language_code: en
├ chat
┊ ├ id: 106596774
┊ ├ first_name: Komron
┊ ├ last_name: Aripov
┊ ├ username: tgcode
┊ └ type: private
├ date: 1549290736
└ text: ayye

我尝试过使用treelib python 的库,但它没有为它们的类提供将 json 转换为所需的格式化文本的方法。对于我的用例来说,它似乎也有点太复杂了。

github 有一个适合我的用例的库,但它是用 JavaScript 编写的(无法理解它以进行逆向工程)

最佳答案

这看起来很有趣,所以我尝试了一下:

def custom_display(input, depth = 0):
if depth == 0:
output_string = "Message\n"
else:
output_string = ""
if type(input) is dict:
final_index = len(input)-1
current_index = 0
for key, value in input.items():
for indent in range(0, depth):
output_string += " ┊ "
if current_index == final_index:
output_string += " └ "
else:
output_string += " ├ "
current_index += 1
if type(value) is dict:
output_string += key + '\n' + custom_display(value, depth + 1)
else:
output_string += key + ": " + custom_display(value, depth+1) + '\n'
else:
output_string = str(input)

return output_string

使用,

dict_input = {
"message_id": 445793,
"from": {
"id": 106596774,
"is_bot": False,
"first_name": "Komron",
"last_name": "Aripov",
"username": "tgcode",
"language_code": "en"
},
"chat": {
"id": 106596774,
"first_name": "Komron",
"last_name": "Aripov",
"username": "tgcode",
"type": "private"
},
"date": 1549380586,
"text": "ayye"
}

print(custom_display(dict_input))

给出的输出:

Message
├ message_id: 445793
├ from
┊ ├ id: 106596774
┊ ├ is_bot: False
┊ ├ first_name: Komron
┊ ├ last_name: Aripov
┊ ├ username: tgcode
┊ └ language_code: en
├ chat
┊ ├ id: 106596774
┊ ├ first_name: Komron
┊ ├ last_name: Aripov
┊ ├ username: tgcode
┊ └ type: private
├ date: 1549380586
└ text: ayye

关于python - 如何将 Python 字典树化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54537779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com