Com*_*t69 0 python printing dictionary list output
我目前正在制作一个猜猜谁喜欢上学的游戏,我似乎无法让这个工作.我想要做的是从列表中的所有字典打印字段"名称".
Greg = {"Name":"Greg", "HairLength":"Short", "HairColour":"Brown", "FacialHair":"Yes", "Jewellery":"Yes", "Hat":"No", "Lipstick":"No", "Gender":"Male"}
Chris = {"Name":"Chris", "HairLength":"Long", "HairColour":"Blonde", "FacialHair":"No", "Jewellery":"No","Hat":"Yes", "Lipstick":"Yes", "Gender":"Male"}
Jason = {"Name":"Jason", "HairLength":"Short", "HairColour":"Brown", "FacialHair":"Yes", "Jewellery":"No","Hat":"Yes", "Lipstick":"No", "Gender":"Male"}
Clancy = {"Name":"Clancy", "HairLength":"Bald", "HairColour":"Red", "FacialHair":"Yes", "Jewellery":"No", "Hat":"No","Lipstick":"No", "Gender":"Male"}
Betty = {"Name":"Betty", "HairLength":"Short", "HairColour":"Blonde", "FacialHair":"No", "Jewellery":"Yes","Hat":"Yes", "Lipstick":"Yes", "Gender":"Female"}
Helen = {"Name":"Helen", "HairLength":"Short", "HairColour":"Brown", "FacialHair":"No", "Jewellery":"No", "Hat":"No","Lipstick":"Yes", "Gender":"Female"}
Selena = {"Name":"Selena", "HairLength":"Long", "HairColour":"Brown", "FacialHair":"No", "Jewellery":"Yes","Hat":"No", "Lipstick":"No", "Gender":"Female"}
Jacqueline = {"Name":"Jacqueline", "HairLength":"Long", "HairColour":"Red", "FacialHair":"Yes", "Jewellery":"Yes", "Hat":"No","Lipstick":"No", "Gender":"Female"}
AISuspects = ([Greg, Chris, Jason, Clancy, Betty, Selena, Helen,
Jacqueline])
UserSuspects = ([Greg, Chris, Jason, Clancy, Betty, Selena, Helen, Jacqueline])
print("AISuspects:")
#Here i want it to print the field "Name" in every dictionary within the list AISuspects
print("UserSuspects:")
#Here i want it to print the field "Name" in every dictionary within the list UserSuspects
Run Code Online (Sandbox Code Playgroud)
解决方案后的预期输出和电流输出:
AI嫌疑人:['Greg','Chris','Jason','Clancy','Betty','Selena','Helen','Jacqueline']
网友嫌疑人:['Greg','Chris','Jason','Clancy','Betty','Selena','Helen','Jacqueline']
您可以使用列表推导来获取所有嫌疑人姓名的列表
suspects_names = [suspect['Name'] for suspect in AISuspects]
Run Code Online (Sandbox Code Playgroud)
然后你可以使用 print(' '.join(suspect_names))
如果您不介意在新行中打印每个名称,只需使用for循环:
for suspect in AISuspects:
print(suspect['Name'])
Run Code Online (Sandbox Code Playgroud)
在列表定义周围处理这些括号,你不需要它们,它们通常用于定义元组,所以我将它们删除它们