Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 打印字典列表的键和值_Python - Fatal编程技术网

Python 打印字典列表的键和值

Python 打印字典列表的键和值,python,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'

我试图打印字典列表中的键和值,我希望输出如下所示

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
我犯了什么错误?如何查看键和值

 for key,values in sub.items():

     Print(key, " : ", value)

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

学生
是一个列表。您需要迭代此列表以获取每个字典。然后,对于每个字典,您需要迭代其键值对,以使用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))
其中:

名-迈克尔,姓-乔丹
名字-约翰,姓-罗萨莱斯
名字-马克,姓-吉伦
名字-KB,姓氏-Tonel
别致的一行:

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

您可以使用
.items()
访问python词典中的(键、值)对。除此之外,很难知道如何提供帮助,因为您的代码不可用于。。。在中,就像使用JS一样