[英]print key and value of list of dictionaries
我正在嘗試從字典列表中打印鍵和值,並且我希望 output 看起來像這樣。
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))
我得到 output 只有鍵而不是值
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 方法。解壓縮鍵值元組,您可以隨意使用它們。
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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.