我需要创建一个for循环,该循环会在每次检测到不存在的键时生成一个新的嵌套字典.我正在从以前的函数中获取外部字典的信息.
>它将需要创建一个字典,以可用的运动作为其键,并以字典作为其
值.
>在内部词典中,运动员名称将用作其键和奖牌数
(整数)将为其值.
键=运动,价值= {:}
CSE 231春季2019
>该函数将从get_country_stats()的字典中循环查找
运动员,运动和奖牌.请注意,当您想为一项新运动添加一名运动员时,您需要
首先为该运动创建一个空字典,然后再向其添加运动员.
>奖章的类型(金,银,铜)与我们的新词典无关,它们都是
视为1枚勋章.
我启动了两个空字典,外字典和内字典.然后创建一个外部for循环,该循环遍历所有键值对并返回一个列表
def display_best_athletes_per_sport(Athlete,Country,Sports):
medals = 0
outer_dict = {}
inner_dict = {}
for key,value in Country.items():
for item in value:
athlete = item[0]
medals = item[5]
sport = item[3]
inner_dict = {athlete:medals}
outer_dict = {sport:inner_dict}
if sport not in outer_dict:
new_dict[sport] = value[i]
if medals in value:
medals += 1
else:
medals = 1
如果找不到所需的键(运动),我希望能够生成新的外部词典,每次为特定运动员找到奖牌时,都要更新内部词典的值.
{'FIN': [
('Juhamatti Tapio Aaltonen','Finland',2014,'ice hockey',"ice hockey men's ice hockey",'bronze'),('Paavo Johannes Aaltonen',1948,'gymnastics',"gymnastics men's individual all-around","gymnastics men's team all-around",'gold'),"gymnastics men's horse vault","gymnastics men's pommelled horse",1952,'bronze')],'NOR': [
('Kjetil Andr Aamodt','Norway',1992,'alpine skiing',"alpine skiing men's super g",('Kjetil Andr Aamodt',"alpine skiing men's giant slalom",1994,"alpine skiing men's downhill",'silver'),"alpine skiing men's combined",2002,2006,('Ann Kristin Aarnes',1996,'football',"football women's football",'NED': [('Pepijn Aardewijn','Netherlands','rowing',"rowing men's lightweight double sculls",'silver')]}
最佳答案
好吧,这只猫现在已经出了书.所以这是我的看法.我认为将检查条目显示在dict中与将某些内容添加到该条目分开是很好的.因此,当您添加条目时,它始终“尚无任何内容”.这样,无论条目是否存在,都可以用相同的方式对待“将下一项添加到条目”.鉴于此,正如我所看到的,这是您想要做什么的基本概念:
def display_best_athletes_per_sport(Athlete,Sports):
outer_dict = {}
for key,value in Country.items():
for item in value:
athlete = item[0]
medals = item[5]
sport = item[3]
if sport not in outer_dict:
outer_dict[sport] = {}
if athlete not in outer_dict[sport]:
outer_dict[sport][athlete] = 0
outer_dict[sport][athlete] += 1
pprint(outer_dict)
结果如下:
{'alpine skiing': {'Kjetil Andr Aamodt': 8},'football': {'Ann Kristin Aarnes': 1},'gymnastics': {'Paavo Johannes Aaltonen': 5},'ice hockey': {'Juhamatti Tapio Aaltonen': 1},'rowing': {'Pepijn Aardewijn': 1}}