本文實例講述了Python字典及字典基本操作方法。分享給大家供大家參考,具體如下:
字典是一種通過名字或者關鍵字引用的得數據結構,其鍵可以是數字、字符串、元組,這種結構類型也稱之為映射。字典類型是Python中唯一內建的映射類型,基本的操作包括如下:
(1)len():返回字典中鍵—值對的數量;
(2)d[k]:返回關鍵字對于的值;
(3)d[k]=v:將值關聯到鍵值k上;
(4)del d[k]:刪除鍵值為k的項;
(5)key in d:鍵值key是否在d中,是返回True,否則返回False。
一、字典的創建
1.1 直接創建字典
d={'one':1,'two':2,'three':3}print dprint d['two']print d['three']運算結果:
=======RESTART: C:/Users/Mr_Deng/Desktop/test.py======={'three': 3, 'two': 2, 'one': 1}23>>>1.2 通過dict創建字典
# _*_ coding:utf-8 _*_items=[('one',1),('two',2),('three',3),('four',4)]print u'items中的內容:'print itemsprint u'利用dict創建字典,輸出字典內容:'d=dict(items)print dprint u'查詢字典中的內容:'print d['one']print d['three']運算結果:
=======RESTART: C:/Users/Mr_Deng/Desktop/test.py=======items中的內容:[('one', 1), ('two', 2), ('three', 3), ('four', 4)]利用dict創建字典,輸出字典內容:{'four': 4, 'three': 3, 'two': 2, 'one': 1}查詢字典中的內容:13>>>或者通過關鍵字創建字典
# _*_ coding:utf-8 _*_d=dict(one=1,two=2,three=3)print u'輸出字典內容:'print dprint u'查詢字典中的內容:'print d['one']print d['three']
運算結果:
=======RESTART: C:/Users/Mr_Deng/Desktop/test.py=======輸出字典內容:{'three': 3, 'two': 2, 'one': 1}查詢字典中的內容:13>>>二、字典的格式化字符串
# _*_ coding:utf-8 _*_d={'one':1,'two':2,'three':3,'four':4}print dprint "three is %(three)s." %d運算結果:
=======RESTART: C:/Users/Mr_Deng/Desktop/test.py======={'four': 4, 'three': 3, 'two': 2, 'one': 1}three is 3.>>>三、字典方法
3.1 clear函數:清除字典中的所有項
# _*_ coding:utf-8 _*_d={'one':1,'two':2,'three':3,'four':4}print dd.clear()print d運算結果:
=======RESTART: C:/Users/Mr_Deng/Desktop/test.py======={'four': 4, 'three': 3, 'two': 2, 'one': 1}{}>>>請看下面兩個例子
3.1.1
# _*_ coding:utf-8 _*_d={}dd=dd['one']=1d['two']=2print ddd={}print dprint dd運算結果:
=======RESTART: C:/Users/Mr_Deng/Desktop/test.py======={'two': 2, 'one': 1}{}{'two': 2, 'one': 1}>>>
新聞熱點
疑難解答