[英]Python - How can i print a certain dictionary field from many dictionaries within a list?
我目前正在研究喜歡游戲的Guess Who,但我似乎無法使其正常工作。 我想做的是從列表中下面所有詞典中打印“名稱”字段。
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
解決后的預期輸出和電流輸出:
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]
然后可以使用print(' '.join(suspect_names))
如果您不介意在新行中打印每個名稱,請使用for循環:
for suspect in AISuspects:
print(suspect['Name'])
請注意列表定義周圍的那些括號,您不需要它們,它們通常用於定義元組,因此我將擺脫它們
UserSuspects = [Greg['Name'], Chris['Name'],Jason['Name'], Clancy['Name'], Betty['Name'], Selena['Name'], Helen['Name'], Jacqueline['Name']]
print UserSuspects
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.