【Python基础】字典的嵌套

本文标识 : P00017

本文编辑 : 采药

编程工具 : Python

阅读时长 : 5分钟


嵌套

今天主要了解一下字典的嵌套。

很多时候,我们需要将一系列字典存储在列表中,或者将列表作为值存储在字典里,这就是嵌套。

字典列表

我们有一些关于描述卡片的信息,每张卡片都是有颜色和数字组成。

alien0={'color':'green','points':5}  alien1={'color':'yellow','points':10}  alien2={'color':'yellow','points':15}    aliens=[alien0,alien1,alien2]  for alien in aliens:    print(alien)

输出结果:

{'color': 'green', 'points': 5}  {'color': 'yellow', 'points': 10}  {'color': 'yellow', 'points': 15}

首先我们定义了三个字典,每个字典代表一个卡牌,我们将三个字典存入一个列表中,这就是嵌套。

我们再用代码自动生成30个卡牌

aliens=[]  for alien_number in range(30):      new_alien={'color':'green','points':5}      aliens.append(new_alien)    for alien in aliens[:5]:#显示前5个卡牌      print(alien)  print("······")  print("卡牌总数: "+str(len(aliens)))

输出结果:

{'color': 'green', 'points': 5}  {'color': 'green', 'points': 5}  {'color': 'green', 'points': 5}  {'color': 'green', 'points': 5}  {'color': 'green', 'points': 5}  ······  卡牌总数: 30

但是这些卡牌都一模一样,现在我们需要将卡牌的前三个修改为黄色

aliens=[]  for alien_number in range(30):      new_alien={'color':'green','points':5}      aliens.append(new_alien)    for alien in aliens[:5]:#显示前5个卡牌      print(alien)  print("······")  print("卡牌总数: "+str(len(aliens)))    for alien in aliens[0:3]:      alien['color']='yellow'    #显示前5个卡牌  for alien in aliens[0:5]:      print(alien)

结果:

{'color': 'green', 'points': 5}  {'color': 'green', 'points': 5}  {'color': 'green', 'points': 5}  {'color': 'green', 'points': 5}  {'color': 'green', 'points': 5}  ······  卡牌总数: 30  {'color': 'yellow', 'points': 5}  {'color': 'yellow', 'points': 5}  {'color': 'yellow', 'points': 5}  {'color': 'green', 'points': 5}  {'color': 'green', 'points': 5}

字典中存列表

有时候我们需要在字典中存储列表,比如每个人喜欢的编程语言可能有好几个。

fav_languages={      'jen':['python','ruby'],      'sarah':['c'],      'edward':['ruby','go'],      'phil':['python','haskell']                }    for name,languages in  fav_languages.items():      print("n" + name.title() +"' favorite language are:")      for language in languages :          print("t"+language.title())

输出结果:

Edward' favorite language are:    Ruby    Go    Jen' favorite language are:    Python    Ruby    Phil' favorite language are:    Python    Haskell    Sarah' favorite language are:    C

字典中存字典

在字典中可以嵌套字典,但是这样代码就稍微复杂一点。比如你有很多网站用户,每个都有自己的用户名,可作为键,每个用户的信息存储在一个字典。

users = {      'aeinstein':{          'first':'albert',          'last':'einstein',          'location':'princeton',      },      'mcurie':{           'first':'marie',          'last':'curie',          'location':'paris',      }  }    for username,user_info in users.items():      print("nUsername: "+ username)      full_name=user_info['first'] +" "+user_info['last']      location = user_info['location']      print("tFull name: "+full_name.title())      print("tlocation: "+location.title())

输出结果:

Username: mcurie    Full name: Marie Curie    location: Paris    Username: aeinstein    Full name: Albert Einstein    location: Princeton

期待您的进步