国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python字典及字典基本操作方法詳解

2020-02-22 23:03:56
字體:
來源:轉載
供稿:網友

本文實例講述了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}>>>            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 西贡区| 睢宁县| 工布江达县| 黄骅市| 花莲市| 大姚县| 衡水市| 商河县| 灵寿县| 聊城市| 龙川县| 夏河县| 彝良县| 临汾市| 西城区| 高密市| 呈贡县| 安丘市| 蓬溪县| 疏附县| 鸡西市| 广德县| 彭水| 饶平县| 仁寿县| 郑州市| 察雅县| 临武县| 蓬溪县| 通化市| 万荣县| 嘉荫县| 庆阳市| 周宁县| 瑞丽市| 翁牛特旗| 江津市| 安平县| 永吉县| 景东| 同仁县|