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

时间:2019-03-29 04:37:06

标签: python dictionary nested

我的作业问题之一是使用嵌套词典在一行上打印。我该怎么办?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您可以使用print的多个参数以空格分隔它们(可以通过sep参数进行更改):

print(employees[0]["employee_id"], employees[1]["employee_id"])

但是,如果您想打印出所有男性雇员的身份证,则有几种选择:

  1. for循环:

    for employee in employees:
        if employee["title"] == "Mr":
            print(employee["employee_id"], end=" ")
    
  2. 参数解包:

    male_employees = [employee["employee_id"] for employee in employees if employee["title"] == "Mr"]
    print(*male_employees)
    
  3. str.join

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