如何从嵌套字典中打印多个值?

我的作业问题之一是使用嵌套字典在一行上打印。我怎样才能做到这一点?


翻阅古今
浏览 175回答 2
2回答

慕姐4208626

for employee in employees:    if employee["title"] == "Mr":        print(employee["employee_id"])        print(employee["lastname"], employee["firstname"])

冉冉说

您可以使用 的多个参数print用空格分隔它们(可以用sep参数更改):print(employees[0]["employee_id"], employees[1]["employee_id"])但是,如果您想打印出所有男性员工的 ID,您有几个不同的选择:for 环形:for employee in employees:    if employee["title"] == "Mr":        print(employee["employee_id"], end=" ")参数解包:male_employees = [employee["employee_id"] for employee in employees if employee["title"] == "Mr"]print(*male_employees)str.joinmale_employees = [employee["employee_id"] for employee in employees if employee["title"] == "Mr"]print(" ".join(male_employees))特别是对于家庭作业问题,使用for循环的第一个选项是最直观的。编辑:要打印名称,您可以使用格式字符串:for employee in employees:    if employee["title"] == "Mr":        print("{0}, {1}".format(employee["lastname"], employee["firstname"]), end=" ")如果你想玩得更开心,这是一个选择:for employee in employees:    if employee["title"] == "Mr":        print("{lastname}, {firstname}".format(**employee), end=" ")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python