我刚刚开始编写本学期的编码,所以如果你能用简单的方法来帮我找到答案,我会很感激。基本上,我只是希望它打印每个字典的名称,然后列出它的内容。哦,只是你知道,我实际上甚至不喜欢体育运动,这只是我之前想要改进的家庭作业。这就是我所得到的,是的,我知道它并不像我想要的那样工作:
football = {
'favorite player': 'Troy Aikman',
'team': 'Dallas Cowboys',
'number': '8',
'position': 'quarterback'
}
baseball = {
'favorite player': 'Jackie Robinson',
'team': 'Brooklyn Dodgers',
'number': '42',
'position': 'second baseman'
}
hockey = {
'favorite player': 'Wayne Gretzky',
'team': 'New York Rangers',
'number': '99',
'position': 'center'
}
sports = [football, baseball, hockey]
my_sports = ['Football', 'Baseball', 'Hockey']
for my_sport in my_sports:
print(my_sport)
for sport in sports:
for question, answer in sport.items():
print(question.title + ": " + answer)
print("\n")
我想要打印:
Football
Favorite player: Troy Aikman
Team: Dallas Cowboys
Number: 8
Position: quarterback
Baseball:
Favorite player: Jackie Robinson
Team: Brooklyn Dodgers
Number: 42
Position: second baseman
......等等。我如何实现我想要的结果?越简单越好,请使用Python 3,我对Python 2一无所知。
答案 0 :(得分:1)
my_sports = {'Football': football, 'Baseball' : baseball, 'Hockey' : hockey}
for key,value in my_sports.items():
print(key)
for question, answer in value.items():
print(question + ": " + answer)
print("\n")
答案 1 :(得分:0)
<强>更新:强>
我编辑我的答案,现在下面的代码有效:
my_sports = {'Football': football, 'Baseball' : baseball, 'Hockey' : hockey}
for key,value in my_sports.items():
print(key)
for question, answer in value.items():
print(question + ": " + answer)
print("\n")
结果如下:
Football
Favorite Player: Troy Aikman
Team: Dallas Cowboys
Number: 8
Position: quarterback
Baseball
Favorite Player: Jackie Robinson
Team: Brooklyn Dodgers
Number: 42
Position: second baseman
Hockey
Favorite Player: Wayne Gretzky
Team: New York Rangers
Number: 99
Position: center
此处的代码: https://repl.it/MOBO/3
答案 2 :(得分:0)
你可以试试这个:
sports = {"football":football, "baseball":baseball, "hockey":hockey}
for a, b in sports.items():
print(a)
for c, d in b.items():
print("{}: {}".format(c, d))
输出:
football
position: quarterback
favorite player: Troy Aikman
number: 8
team: Dallas Cowboys
baseball
position: second baseman
favorite player: Jackie Robinson
number: 42
team: Brooklyn Dodgers
hockey
position: center
favorite player: Wayne Gretzky
number: 99
team: New York Rangers
答案 3 :(得分:0)
内置的zip
函数似乎是从两个列表中组合和配对元素的最简单方法。以下是如何使用它:
sports = [football, baseball, hockey]
my_sports = ['Football', 'Baseball', 'Hockey']
for my_sport, sport in zip(my_sports, sports):
print('\n'.join((
'{}', # name of sport
'Favorite player: {favorite player}',
'Team: {team}',
'Number: {number}',
'Position: {position}')).format(my_sport, **sport) + '\n'
)