python3學習筆記7--字典

  • 一個簡單的字典
alien_0 = {'color':'green','points':5}

print(alien_0['color'])
print(alien_0['points'])
  • 使用字典

在Python中,字典是一系列鍵---值對。每個鍵都有與之相關聯的值。在Python中,字典用{}中的一系列鍵---值對錶示。

鍵---值對 是兩個相關聯的值。指定鍵時,Python返回與之相關聯的值。鍵和值之間用冒號分隔,而鍵值對之間用逗號隔開。

1、訪問字典中的值

獲取與鍵相關的值,可依次指定字典名個放在方括號內的鍵。

2、添加鍵---值對

字典是動態結構,可隨時在其中添加鍵---值對。要添加鍵---值對,可依次指定字典名、用方括號括起的鍵和相關聯的值。

3、創建空字典

alien_0['color'] = 'green'

alien_0['points'] = 5

print(alien_0)

4、修改字典中的值

要修改字典中的值,可依次指定字典名、用方括號括起的鍵以及與該鍵相關聯的新值。

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

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

5、刪除鍵---值對

可使用del  語句將對應的鍵---值對徹底刪除

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

del alien_0['points']
print(alien_0)

6、有類似對象組成的字典

favorite_languages = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'perl',
}
print("Sarah's favorite language is "+favorite_languages['sarah'].title()
      +".")
  • 遍歷字典

1、遍歷所有的鍵---值對

user_0 = {
    'username':'efermi',
    'frist':'enrico',
    'last':'fermi',
}
for key ,value in user_0.items():
    print("\n Key:"+ key)
    print("\n Value:"+ value)

2、遍歷字典中的所有鍵

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

3、按順序遍歷字典中的所有鍵

字典總是明確地記錄鍵和值之間的關聯聯繫。但獲取字典的元素時,獲取順序是不可預測的。要以特定的順序返回元素,一種是在for 循環中對返回的鍵進行排序,可以使用函數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.")

4、遍歷字典中的所有值

顯示字典中包含的值,可使用方法 values() ,它返回一個值列表。

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())

爲剔除重複項,可使用集 合(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())
  • 嵌套

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

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)
# 創建一個用於存儲外星人的空列表
aliens = []
# 創建30個綠色的外星人
for alien_number in range(30):
    new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
    aliens.append(new_alien)
# 顯示前五個外星人
for alien in aliens[:3]:
    if alien['color'] == 'green':
        alien['color'] = 'yellow'
        alien['points'] = 10
for alien in aliens[0:5]:
    print(alien)
print("...")
# 顯示創建了多少個外星人
print("Total number of aliens: " + str(len(aliens)))

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)

3、在字典中存儲字典

users = {
    'aeinstein': {
        'first': 'albert',
        'last': 'einstein',
        'location': 'princeton',
    },
    'mcurie': {
        'first': 'marie',
        'last': 'curie',
        'location': 'paris',
    },
}
for username ,user_info in users.items():
    print("\n Username: " + username)
    full_name = user_info['first'] + " " + user_info['last']
    location = user_info['location']
    print("\t Full name: " + full_name)
    print("\t Location: " + location.title())

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章