打印字典列表的键和值

时间:2021-05-25 17:47:06

标签: python

我正在尝试从字典列表中打印键和值,并且我希望输出看起来像这样。

first_name - Michael, last_name - Jordan
first_name - John, last_name - Rosales
first_name - Mark, last_name - Guillen
first_name - KB, last_name - Tonel 

这是我写的代码

students = [
         {'first_name':  'Michael', 'last_name' : 'Jordan'},
         {'first_name' : 'John', 'last_name' : 'Rosales'},
         {'first_name' : 'Mark', 'last_name' : 'Guillen'},
         {'first_name' : 'KB', 'last_name' : 'Tonel'}
    ]
def listd (somelist):
    for key , value in students:
        print(key, '-', value)
print (listd(students))

我得到的输出只有键而不是值

first_name - last_name
first_name - last_name
first_name - last_name
first_name - last_name
None

我犯了什么错误,如何查看键和值?

2 个答案:

答案 0 :(得分:1)

对于学生子:

 for key,values in sub.items():

     Print(key, " : ", value)

只需从列表中提取每个子字典并在循环中对每个子字典调用字典的 item 方法。解压键值元组,您可以随心所欲地使用它们..

答案 1 :(得分:0)

students 是一个列表。您需要遍历此列表以获取每个字典。然后,对于每个字典,您需要迭代其键值对,以使用 f 字符串按照您想要的方式对其进行格式化。然后,您可以使用 str.join() 用逗号连接这些值以打印您想要的内容。

for student in students:
    to_print = []
    for key, value in student.items():
        to_print.append(f"{key} - {value}")

    # Now, to_print is a list that contains two elements:
    # ["first_name - Michael", "last_name - Jordan"]
    print(", ".join(to_print))

给出:

first_name - Michael, last_name - Jordan
first_name - John, last_name - Rosales
first_name - Mark, last_name - Guillen
first_name - KB, last_name - Tonel

花哨的单线:

print(*(", ".join(f"{key} - {value}" for key, value in student.items()) for student in students), sep="\n")