Python編程入門到實踐 - 筆記( 6 章)


第 6 章主要練習了各類字典,如下內容python

什麼是字典ruby

字典中 鍵-值 的關係app

一個簡單的字典ide

經過字典中的鍵查找其對應的值spa

在字典中添加 鍵-值對象

修改字典中的值排序

遍歷字典中的鍵值對 items( )it

遍歷字典中的鍵 keys( )io

遍歷字典中的值 value( )ast

遍歷字典中的值而且去重複 set( )

列表中嵌套字典

經過 for 循環將字典添加到同一個列表中

在字典中存儲列表並打印



什麼是字典?

我本身來個不成熟的總結吧:就是一個高級列表,爲啥說是高級列表,由於列表中的元素是單一的,沒有屬性

而字典能夠指定屬性。好比說:你叫張三,在列表中只能存儲張三這個姓名,而字典能夠儲存爲 --- 姓名:張三

字典使用花括號 { }

列表使用中括號 [ ]

元組使用小括號 ( )



字典中的 鍵-值 關係

好比這個簡單的列表 alien_0 = {'color': 'green', 'points': 5}

color 是鍵,green 是值



一個簡單的字典

經過 鍵 獲取相關的 值

------------------------------------------------

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

------------------------------------------------

green  
5



如何引用的字典中的值

將經過字典中的鍵獲取到的值定義一個變量,並在 print 中引用

------------------------------------------------------------------------

alien_0 = {'color': 'green', 'points': 5}  
new_points = alien_0['points']    
print("You just earned " + str(new_points) + " points!")

------------------------------------------------------------------------

You just earned 5 points!  


 

添加 鍵-值

在 alien_0 字典中在添加兩個鍵值對

----------------------------------------------------------------------------

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, 'x_position': 0, 'y_position': 25}   


 

在空字典中添加鍵值對

----------------------------------

alien_0 = {}

alien_0['color'] = 'green'  
alien_0['points'] = 5

print(alien_0)

-----------------------------------

{'color': 'green', 'points': 5}



修改字典中的值

---------------------------------------------------------------

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.


    

刪除鍵值對

和列表相同,使用 del 刪除字典中的鍵值(永久性刪除)

------------------------------------------------

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

del alien_0['points']  
print(alien_0)

-------------------------------------------------

{'color': 'green', 'points': 5}  
{'color': 'green'}



由相似對象組成的字典

經過鍵調用字典中的值

-------------------------------------------------------------------------------------------

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

print("Sarah's favorite language is " + favorite_languages['sarah'].title() + ".")

-------------------------------------------------------------------------------------------

Sarah's favorite language is C.



items( ) 遍歷全部的鍵值對

能夠經過一個簡單的 for 循環遍歷這個字典

-----------------------------------------

user_0 = {  
     'username': 'efermi',    
     'first': 'enrico',    
     'last': 'fermi',    
}

for key, value in user_0.items():  
     print("\nKey: " + key)    
     print("Value: " + value)

------------------------------------------

Key: username  
Value: efermi


Key: first  
Value: enrico


Key: last  
Value: fermi



遍歷字典的一個小實例

-------------------------------------------------------------------------------------------

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

for name, language in favorite_languages.items():  
     print(name.title() + "'s favorite language is " + language.title() + ".")

-------------------------------------------------------------------------------------------

Jen's favorite language is Python.  
Sarah's favorite language is C.    
Edward's favorite language is Ruby.    
Phil's favorite language is Python.



keys( ) 遍歷字典全部的鍵

其實不加 keys() 也不要緊,由於字典默認就會遍歷全部的鍵

這樣更清楚而已

--------------------------------------------------

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

for name in favorite_languages.keys():  
     print(name.title())

---------------------------------------------------

Jen  
Sarah    
Edward    
Phil



使用 for 循環遍歷字典中內容

並定義一個列表作 if 判斷,若是 for 循環中有列表的元素

就在打印一句話

-------------------------------------------------------------------------------------------

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

friends = ['phil', 'sarah']  
for name in favorite_languages.keys():    
     print(name.title())

     if name in friends:  
          print(" Hi " + name.title() + ", I see your favorite language is " + favorite_languages[name].title() + "!")

-------------------------------------------------------------------------------------------

Jen  
Sarah    
  Hi Sarah, I see your favorite language is C!    
Edward    
Phil    
  Hi Phil, I see your favorite language is Python!



使用 keys() 遍歷,檢查字典中的 鍵 是否是存在指定的字符,並作 if 判斷

若是 erin 不存在字典中,就指定 print

-----------------------------------------------------

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

if 'erin' not in favorite_languages.keys():  
     print("Erin, please take our poll!")

------------------------------------------------------

Erin, please take our poll!



按順序遍歷字典中的全部鍵

調用 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.



value( ) 遍歷字典中的全部值並大寫

---------------------------------------------------------------------------

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

print("The following languages have been mentioned:")  
for language in favorite_languages.values():    
     print(language.title())

---------------------------------------------------------------------------

The following languages have been mentioned:  
Python    
C    
Ruby    
Python



在數據比較多的狀況下,可使用 set( ) 去除重複項

set( ) 合集

--------------------------------------------------------------------------

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

print("The following languages have been mentioned:")  
for language in set(favorite_languages.values()):    
     print(language.title())

--------------------------------------------------------------------------

The following languages have been mentioned:  
Python    
C    
Ruby



嵌套:列表中嵌套字典

----------------------------------------------------

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}



使用循環建立字典列表

for 循環 30 次,將 new_alien 的字典放到 aliens 列表中

打印前 5 次

用 len( ) 計算 aliens 列表的長度

---------------------------------------------------------------------------

aliens = []

for alien_number in range(30):  
     new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}    
     aliens.append(new_alien)

for alien in aliens[:5]:  
     print(alien)    
print("...")

print("Total number of aliens: " + str(len(aliens)))

---------------------------------------------------------------------------

{'color': 'green', 'points': 5, 'speed': 'slow'}  
{'color': 'green', 'points': 5, 'speed': 'slow'}    
{'color': 'green', 'points': 5, 'speed': 'slow'}    
{'color': 'green', 'points': 5, 'speed': 'slow'}    
{'color': 'green', 'points': 5, 'speed': 'slow'}    
...    
Total number of aliens: 30



在字典循環中進行比較並更改值

先定義一個空列表 aliens,將 new_alien 的列表循環 30 次加到 aliens 列表中

第二個 for 循環先對 aliens 切片,進行判斷

==  是進行比較

=  是進行更改

第三個 for 循環是打印 aliens 列表的前 5 個元素,能夠看出修改後的不一樣

----------------------------------------------------------------------------

aliens = [ ]

for alien_number in range(30):  
     new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}    
     aliens.append(new_alien)

for alien in aliens[0:3]:  
     if alien['color'] == 'green':    
          alien['color'] = 'yellow'    
          alien['speed'] = 'medium'    
          alien['points'] = 10

for alien in aliens[0:5]:  
     print(alien)    
print("...")

----------------------------------------------------------------------------

{'color': 'yellow', 'points': 10, 'speed': 'medium'}  
{'color': 'yellow', 'points': 10, 'speed': 'medium'}    
{'color': 'yellow', 'points': 10, 'speed': 'medium'}    
{'color': 'green', 'points': 5, 'speed': 'slow'}    
{'color': 'green', 'points': 5, 'speed': 'slow'}    
...



在字典中存儲列表

在 pizza 字典中 toppings 列表中有兩個值,均可以分別打印

------------------------------------------------------------------------------------------------------------------

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



對字典進行 for 循環,在將字典中的列表的元素再次進行循環

-------------------------------------------------------------------------------

favorite_languages = {  
     'jen': ['python', 'ruby'],    
     'sarah': ['c'],    
     'edward': ['ruby', 'go'],    
     'phil': ['python', 'haskell'],    
}

for name, languages in favorite_languages.items():  
     print("\n" + name.title() + "'s favorite languages are:")    
     for language in languages:    
          print("\t" + language.title())

-------------------------------------------------------------------------------

Jen's favorite languages are:  
    Python    
    Ruby

Sarah's favorite languages are:  
    C

Edward's favorite languages are:  
    Ruby    
    Go

Phil's favorite languages are:       Python        Haskell

相關文章
相關標籤/搜索