【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

期待您的進步