如何在列表中以可读格式显示字典中的数据?



数据需要以这种格式存储

data = {'admin': [{'title': 'Register Users with taskManager.py', 'description': 'Use taskManager.py to add the usernames and passwords for all team members that will be using this program.', 'due date': '10 Oct 2019', 'date assigned': '20 Oct 2019', 'status': 'No'}, {'title': 'Assign initial tasks', 'description': 'Use taskManager.py to assign each team member with appropriate tasks', 'due date': '10 Oct 2019', 'date assigned': '25 Oct 2019', 'status': 'No'}], 'new user': [{'title': 'Take out trash', 'description': 'Take the trash can down the street', 'due date': '10 oct 2022', 'date assigned': '20 Oct 2022', 'status': 'No'}]}

我需要像这样显示这些数据:

user: admin
title: Register Users with taskManager.py
description: Use taskManager.py to add the usernames and passwords for all team members that will be using this program
date assigned: 10 Oct 2019
due date: 20 Oct 2022
status: No

title: Assign initial tasks
description: Use taskManager.py to assign each team member with appropriate tasks
date assigned: 10 Oct 2019
due date: 25 Oct 2019
status: No
user: new user
title: Take out trash
description: Take the trash can down the street
date assigned: 10 Oct 2022
due date: 20 Oct 202
status: No

我该怎么做?

试试这个:

dict = #your dict here
for user in dict.values():
print(f"user: {user}")
for k, v in dict[user]: # selects sub dicts
print (f"{k}: {v})

你基本上有一个密集嵌套的结构所以如果这是你数据的最终结构那么最简单的方法就是用硬编码的方式使用dict.items()来拆解它,像这样:

data = {'admin': [{'title': 'Register Users with taskManager.py', 'description': 'Use taskManager.py to add the usernames and passwords for all team members that will be using this program.', 'due date': '10 Oct 2019', 'date assigned': '20 Oct 2019', 'status': 'No'}, {'title': 'Assign initial tasks', 'description': 'Use taskManager.py to assign each team member with appropriate tasks', 'due date': '10 Oct 2019', 'date assigned': '25 Oct 2019', 'status': 'No'}], 'new user': [{'title': 'Take out trash', 'description': 'Take the trash can down the street', 'due date': '10 oct 2022', 'date assigned': '20 Oct 2022', 'status': 'No'}]}

for user, tasks in data.items():
print("user:", user)
for task in tasks:
print()
for field, value in task.items():
print(f"{field}: {value}")
print()

这会产生期望的输出:

user: admin
title: Register Users with taskManager.py
description: Use taskManager.py to add the usernames and passwords for all team members that will be using this program.
due date: 10 Oct 2019
date assigned: 20 Oct 2019
status: No

title: Assign initial tasks
description: Use taskManager.py to assign each team member with appropriate tasks
due date: 10 Oct 2019
date assigned: 25 Oct 2019
status: No
user: new user
title: Take out trash
description: Take the trash can down the street
due date: 10 oct 2022
date assigned: 20 Oct 2022
status: No

遍历键以打印数据。您可能需要在之后添加额外的格式以提高可读性。

for i in data.keys():
print(f"user: {i}")
for j in data[i]:
for k in j.keys():
print(f"{k}: {j[k]}")

相关内容

  • 没有找到相关文章

最新更新