python3_字典

python3_字典

一.字典的增刪改查


1.定義

在Python中,字典 是一系列鍵—值對。每個鍵都與一個值相關聯,你可以使用鍵來訪問與之相關聯的值。與鍵相關聯的值可以是數字、字符串、列表乃至字典。事實上,可將任何Python對象用作字典中的值。

#定義一個字典
alien_0 = {'color': 'green', 'points': 5} 
print(alien_0['color']) 
print(alien_0['points'])

2.添加鍵 - 值對:

字典名 [‘key值’] = value值

alien_0 = {'color': 'green', 'points': 5}  
print(alien_0)
alien_0['x_position'] = 0 
alien_0['y_position'] = 25  
print(alien_0)

#結果:
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'y_position': 25, 'x_position': 0}

3.修改字典中的值:

字典名 [‘key值’] = 新value值

alien_0 = {'color': 'green'} 
print("The alien is " + alien_0['color'] + ".") 
alien_0['color'] = 'yellow' 
print("The alien is now " + alien_0['color'] + ".")

結果:
The alien is green. 
The alien is now yellow.

4.刪除鍵 - 值對:

對於字典中不再需要的信息,可使用del 語句將相應的鍵—值對徹底刪除。使用del 語句時,必須指定字典名和要刪除的鍵。
!!!刪除的鍵—值對永遠消失了。

del 字典名 [‘key值’] = value值

alien_0 = {'color': 'green', 'points': 5}  
print(alien_0) 
del alien_0['points']  
print(alien_0)

結果爲:
{'color': 'green', 'points': 5} 
{'color': 'green'}

5.字典可選用類似對象的格式

定義好字典後,在最後一個鍵—值對的下一行添加一個右花括號,並縮進四個空格,使其與字典中的鍵對齊。另外一種不錯的做法是在最後一個鍵—值對後面也加上逗號,爲以 後在下一行添加鍵—值對做好準備。

favorite_languages = {    
    'jen': 'python',    
    'sarah': 'c',    
    'edward': 'ruby',    
    'phil': 'python',    
    }

【練習】:

1 人 :使用一個字典來存儲一個熟人的信息,包括名、姓、年齡和居住的城市。該字典應包含鍵first_name 、last_name 、age 和city 。將存儲在該字典中 的每項信息都打印出來。

Xiaofang = {
    'first_name': 'Han',
    'last_name': 'Gao',
    'sex': 'male',
    'year': '18',
    'city': 'Fuzhou'
}
for key, values in Xiaofang.items():
    print(key + " : " + values)

2 喜歡的數字 :使用一個字典來存儲一些人喜歡的數字。請想出5個人的名字,並將這些名字用作字典中的鍵;想出每個人喜歡的一個數字,並將這些數字作爲值存 儲在字典中。打印每個人的名字和喜歡的數字。爲讓這個程序更有趣,通過詢問朋友確保數據是真實的。

dictory = {
    'Xiaofang': '11',
    'ZaZaYang': '8',
    'ZaZaHui': '9'
}
for key, value in dictory.items():
    print(key + "最喜歡的數字是:" + value)

3 詞彙表 :Python字典可用於模擬現實生活中的字典,但爲避免混淆,我們將後者稱爲詞彙表。

  • 想出你在前面學過的5個編程詞彙,將它們用作詞彙表中的鍵,並將它們的含義作爲值存儲在詞彙表中。
  • 以整潔的方式打印每個詞彙及其含義。爲此,你可以先打印詞彙,在它後面加上一個冒號,再打印詞彙的含義;也可在一行打印詞彙,再使用換行符(\n )插 入一個空行,然後在下一行以縮進的方式打印詞彙的含義。
dictionary = {
    'word': '單詞',
    'appale': '蘋果',
    'mellon': '瓜',
    'big older': '大佬'
}
dictionary['word'] = '句子'
# print(dictionary['word'])
for key, value in dictionary.items():
    print(key + "的意思是:" + value)

二.遍歷字典


1.遍歷所有鍵 - 值對:

方法items() ,它返回一個鍵—值對列表

for 鍵,值 in 字典.items():

案例可見上文

2.遍歷字典中的所有鍵:

方法keys() ,返回所有鍵

favorite_languages = {      
    'jen': 'python',      
    'sarah': 'c',      
    'edward': 'ruby',      
    'phil': 'python',      
    } 
for name in favorite_languages.keys():      
    print(name.title()

結果:
Jen 
Sarah 
Phil 
Edward

2.2排序:

函數sorted() 來獲得按特定順序排列的鍵列表的副本:
默認按照字母排序

favorite_languages = {      
    'jen': 'python',      
    'sarah': 'c',      
    'edward': 'ruby',      
    'phil': 'python',      
    } 
for name in sorted(favorite_languages.keys()):    
    print(name.title() + ", thank you for taking the poll.")

結果爲:
Edward, thank you for taking the poll. 
Jen, thank you for taking the poll. 
Phil, thank you for taking the poll. 
Sarah, thank you for taking the poll.

3.遍歷字典中的所有值:

方法values() ,它返回一個值列表,而不包含任何鍵。
方法類似返回鍵

【練習】:

5 河流 :創建一個字典,在其中存儲三條大河流及其流經的國家。其中一個鍵—值對可能是’nile’: ‘egypt’ 。

  • 使用循環爲每條河流打印一條消息,如“The Nile runs through Egypt.”。
  • 使用循環將該字典中每條河流的名字都打印出來。
  • 使用循環將該字典包含的每個國家的名字都打印出來。
information = {
    'Koren': 'a river',
    'Japen': 'b river',
    'China': 'Yellow River',
    'egypt': 'nile'
}
for country, river in information.items():
    print("The " + river + " runs through " + country)

三.嵌套


“嵌套”將一系列字典存儲在列表中,或將列表作爲值存儲在字典中。
你可以在列表中嵌套字典、在字典中嵌套列表甚至在字典中嵌套字典。

1.列表嵌套字典

alien_0 = {'color': 'green', 'points': 5}  
alien_1 = {'color': 'yellow', 'points': 10}  
alien_2 = {'color': 'red', 'points': 15} 

#列表:
aliens = [alien_0, alien_1, alien_2]  
for alien in aliens:      
print(alien)

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

2.字典中嵌套列表

pizza = {      
    'crust': 'thick',      
    # 字典嵌套列表
    'toppings': ['mushrooms','extra cheese'],      
    }  
print("You ordered a " + pizza['crust'] + "-crust pizza " +      
    "with the following toppings:") 
for topping in pizza['toppings']:      
    print("\t" + topping)

結果:
You ordered a thick-crust pizza with the following toppings:    
    mushrooms    
    extra cheese

3.字典中嵌套字典

  users = {      
      'aeinstein': {          
          'first': 'albert',          
          'last': 'einstein',          
          'location': 'princeton',          
          },      
      'mcurie': {          
          'first': 'marie',          
          'last': 'curie',          
          'location': 'paris',          
          },      
      }

【練習】:

7 人 :在爲完成練習6-1而編寫的程序中,再創建兩個表示人的字典,然後將這三個字典都存儲在一個名爲people 的列表中。遍歷這個列表,將其中每個人的所有 信息都打印出來。

Xiaofang = {
    'first_name': 'Han',
    'last_name': 'Gao',
    'sex': 'male',
    'year': '18',
    'city': 'Fuzhou'
}

Xiaofang2 = {
    'first_name': 'Han',
    'last_name': 'Gao',
    'sex': 'male',
    'year': '18',
    'city': 'Fuzhou'
}

Xiaofang3 = {
    'first_name': 'Han',
    'last_name': 'Gao',
    'sex': 'male',
    'year': '18',
    'city': 'Fuzhou'
}

lists = [Xiaofang, Xiaofang2, Xiaofang3]
for list in lists:
    print(list)

9 喜歡的地方 :創建一個名爲favorite_places 的字典。在這個字典中,將三個人的名字用作鍵;對於其中的每個人,都存儲他喜歡的1~3個地方。爲讓這個練 習更有趣些,可讓一些朋友指出他們喜歡的幾個地方。遍歷這個字典,並將其中每個人的名字及其喜歡的地方打印出來。

favorite_places = {
    'peter': ['a', 'b', 'c'],
    'Pill': ['a', 'B', 'c'],
    'Mak': ['A', 'B', 'c']
}
for name, places in favorite_places.items():
    for place in places:
        print(name + "喜歡的地方有:" + place)


結果爲:
peter喜歡的地方有:a
peter喜歡的地方有:b
peter喜歡的地方有:c
Pill喜歡的地方有:a
Pill喜歡的地方有:B
Pill喜歡的地方有:c
Mak喜歡的地方有:A
Mak喜歡的地方有:B
Mak喜歡的地方有:c
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章