python 字典dict

# -*- coding: utf-8 -*-

# ****************************** 創建 ***************************
dict1 = {}

#定義1個元素的字典
dict2 = {'pi': 3.14}
print(dict2)  #{'pi': 3.14}

dict3 = {1: 2}
print(dict3)  #{1: 2}

dict4 = dict([[1, 2], ('a', 'b')])
print(dict4)  #{'a': 'b', 1: 2}

dict5 = {}
dict5['hello'] = 'world'
print(dict5)  #{'hello': 'world'}   相當於查找元素賦值操作,如果存在,則替換該鍵的值,不存在,則創建

#關鍵字參數創建字典
dict7 = dict(hello='world', a='b')
print(dict7)  #{'a': 'b', 'hello': 'world'}

dict6 = dict([[1, 2], ['hello', 'world']])
print(dict6)  #{1: 2, 'hello': 'world'}  這樣寫是沒有問題的
#dict6 = dict(1 = 2, hello = 'world')   #這樣會報錯,不能爲表達式

#創建相同鍵值的字典
dict7 = dict.fromkeys(('a', 'b', 'c'))
print(dict7)  #{'a': None, 'c': None, 'b': None}  不傳參數默認值爲None
dict7 = dict.fromkeys(('d', 'b', 'c'), 'nihao')
print(dict7)  #{'c': 'nihao', 'b': 'nihao', 'd': 'nihao'}  鍵值存在的會修改key對應的值

dict8 = {1:2, 3:4, 3:5}
print(dict8)  #{1: 2, 3: 5}

# ****************************** 增加 ***************************
dict1 = {'a': 'aaa', 'pi':3.14}
dict1['new'] = 'valueNew'
print()

dict2 = {'a': 'b', 'pi': 3.14}
dict2.setdefault('c', 'haha')
print(dict2)  #{'a': 'b', 'c': 'haha', 'pi': 3.14} //增加一個元素,不存在的話默認添加
dict2.setdefault('a', 'aaa')
print(dict2) #{'a': 'b', 'c': 'haha', 'pi': 3.14} //增加一個元素,存在的話不作處理

#dict8[0]  #注意,傳入的是key, 不是索引, 這樣訪問找不到key爲0的就報錯KeyError: 0
print(dict8[3])  #5
print(dict8.get(4), 'bucunzai') #bucunzai  不存在是不報錯,報自己添加的提示

#獲取所有的key值
dict9 = {'hi': 'nihao', 'hello': 'world', 'pi': 3.14}
print(dict9.keys())  #['pi', 'hi', 'hello']

#獲取所有值
print(dict9.values())  #[3.14, 'nihao', 'world']

#獲取所有項
print(dict9.items())  #[('pi', 3.14), ('hi', 'nihao'), ('hello', 'world')]
print(list(dict9.iteritems()))

#查找鍵值是否存在
print(dict9.has_key('hi'))  #True
print(dict9.has_key('ll'))  #False

#清空 & 刪除
del(dict9['hi']) #不存在會報異常
print(dict9)  #{'pi': 3.14, 'hello': 'world'}
print(dict9.pop('pi')) #3.14  刪除key爲'pi'的鍵以及對應的值,返回鍵值
print(dict9.pop('pp', 'not exsit')) #not exsit  默認值用來提示用
print(dict9.popitem())  #('hello', 'world')

dict9.clear()
print(dict9)  #{}  清空變成空的字典,非刪除

del(dict9)  #徹底刪除dict9

dict10 = {'a': 'b', 'pi': 3.14}
dict11 = dict(dict10)
print(dict11)  #{'a': 'b', 'pi': 3.14}
dict12 = dict10.copy()
print(dict12)  #{'a': 'b', 'pi': 3.14}
print(id(dict10)) #4301077312
print(id(dict11)) #4300836944
print(id(dict12)) #4301075913
dict10['a'] = 'bbbb'
print(dict10)  #{'a': 'bbb', 'pi': 3.14}
print(dict11)  #{'a': 'b', 'pi': 3.14}
print(dict12)  #{'a': 'b', 'pi': 3.14}

print('a' in dict10) #true

print(dict12.popitem()) #('a', 'b')

dict1 = {1:'on', 3:'three', 4:'four'}
dict2 = {1:'one', 5:'five'}
dict1.update(dict2)  #{1: 'one', 3: 'three', 4: 'four', 5: 'five'} 通過一個字典更新另一個字典,存在的替換值,不存在的創建
print(dict1)


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