python字典的基本用法總結#附有實例

字典是另一種可變容器模型,且可存儲任意類型對象
字典的每個鍵值(key=>value)對用冒號(:)分割,每個對之間用逗號(,)分割,整個字典包括在花括號({})中 ,格式如下所示:
d = {key1 : value1, key2 : value2 }
鍵必須是唯一的,但值則不必,
值可以取任何數據類型,但鍵必須是不可變的,如字符串,數字或元組。
下面爲對字典的基本用法:

一:訪問字典中的值

方括號指定鍵

aliens = {'color': 'green'}
print(aliens['color'])

結果:
green

二:添加鍵-值對

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

aliens = {'color': 'green', 'points': 5}
print("添加鍵-值對前:" + str(aliens))
aliens['x_position'] = 0
aliens['y_position'] = 25
print("添加鍵-值對後" + str(aliens))

結果:
添加鍵-值對前:{'color': 'green', 'points': 5}
添加鍵-值對後{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}

三:創建一個空字典

aliens = {}
aliens['color'] = 'green'
aliens['points'] = 5
print(aliens)

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

四:修改字典中的值

指定字典名,用方括號括起的鍵以及與該鍵相關聯的新值

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

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

五:刪除鍵-值對

使用del 語句指定字典名和要刪除的鍵

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

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

六:字典遍歷

6.1. 遍歷字典中的鍵-值對

使用字典方法items,它將返回一個鍵-值列表

person = {'first_name': 'chen', 'last_name': 'mc', 'age': 25, "city": 'beijing'}
print("person: " + str(person.items()))
for k, v in person.items():
    print("\nkey: " + k)
    print("value: " + str(v))

結果:
person: dict_items([('first_name', 'chen'), ('last_name', 'mc'), ('age', 25), ('city', 'beijing')])
key: first_name
value: chen

key: last_name
value: mc

key: age
value: 25

key: city
value: beijing

6.2 遍歷字典中的所有鍵

使用方法keys(),它將返回一個鍵列表

person = {'first_name': 'chen', 'last_name': 'mc', 'age': 25, "city": 'beijing'}
print("person-keys: " + str(person.keys()))

結果:
person-keys: dict_keys(['first_name', 'last_name', 'age', 'city'])

可以使用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.

6.3. 遍歷字典中的所有值

使用方法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())

結果:
The following languages have been mentioned:
Python
C
Ruby
Python

剔除字典重複的鍵或者值,可以使用集合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:
C
Ruby
Python

七:字典嵌套

7.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}

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

7.3 在字典中存儲字典

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: aeinstein
	Full name: Albert Einstein
	Location: Princeton

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