1.1字典的定義
- dictionary(字典) 是 除列表以外 Python 之中 最靈活 的數據類型
- 字典同樣可以用來 存儲多個數據通常用於存儲 描述一個 物體 的相關信息
- 列表 是 有序 的對象集合;字典 是 無序 的對象集合
- 字典用 {} 定義
- 字典使用 鍵值對 存儲數據,鍵值對之間使用 ,分隔
- 鍵 key 是索引,值 value是數據,它們之間使用 : 分隔。
- 鍵必須是唯一的, 鍵 只能使用 字符串、數字或 元組
- 值 可以取任何數據類型
<code>xiaoming = {"name": "小明",
"age": 18,
"gender": True,
"height": 1.75}/<code>
![Python關於字典定義及常用方法介紹](http://p2.ttnews.xyz/loading.gif)
字典常用操作方法
1.2 字典常用操作
- 在 ipython3 中定義一個 字典,例如:xiaoming = {}
- 輸入 xiaoming. 按下 TAB 鍵,ipython 會提示 字典 能夠使用的函數如下:
<code>In [1]: xiaoming.
xiaoming.clear xiaoming.items xiaoming.setdefault
xiaoming.copy xiaoming.keys xiaoming.update
xiaoming.fromkeys xiaoming.pop xiaoming.values
xiaoming.get xiaoming.popitem /<code>
<code>#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'phone': '1232'}
print (dict['Name'])
print (dict['phone'])
print (dict['Age'])/<code>
輸出結果為:
<code> print (dict['Name'])
Zara
print (dict['phone'])
1232
print (dict['Age'])
7/<code>
②
修改和增加字典向字典添加新內容的方法是增加新的鍵/值對,修改或刪除已有鍵/值對如下實例:
<code>#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'phone': '9876'}
dict['Age'] = 8 # 更新
dict['school'] = "北大" # 添加
print (dict['Age'])
print (dict['school'])
/<code>
輸出結果為:
<code> print (dict['Age'])
8
print (dict['school'])
北大/<code>
③刪除字典和合併字典
能刪除制定的元素也可直接清空字典,如下實例:
<code>#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name'] # 刪除鍵是'Name'的條目
dict.clear() # 清空字典所有條目
del dict # 刪除字典
dict_new = {'phone':123456}
dict.update(dict_new) #合併字典
print (dict['Name'])
print (dict)/<code>
輸出結果為:
<code>print (dict['Name'])
Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
print (dict['Name'])
KeyError: 'Name'
print (dict)
{'Age': 7, 'Class': 'First', 'phone': 123456}
print (dict)
<class>
/<class>/<module>/<pyshell>/<code>
有關 字典 的 常用操作 可以參照上圖練習
1.3循環遍歷
- 遍歷 就是 依次 從 字典 中獲取所有鍵值對
<code># for 循環內部使用的key的變量 in 字典:
for k in xiaoming:
print("%s: %s" % (k, xiaoming[k]))/<code>
提示:在實際開發中,由於字典中每一個鍵值對保存數據的類型是不同的,所以針對字典的循環遍歷需求並不是很多
1.4 應用場景
- 儘管可以使用 for in 遍歷 字典
- 但是在開發中,更多的應用場景是:使用 多個鍵值對,存儲 描述一個 物體 的相關信息 —— 描述更復雜的數據信息將 多個字典 放在 一個列表 中,再進行遍歷,在循環體內部針對每一個字典進行 相同的處理
<code>card_list = [{"name": "張三",
"qq": "12345",
"phone": "110"},
{"name": "李四",
"qq": "54321",
"phone": "10086"}
]/<code>
閱讀更多 我要學Python 的文章