字典建立python
字典的鍵值對用冒號分割,每對之間用逗號分割,整個字典用花括號中,鍵值惟一,不可變,能夠爲字符串,數字或元祖。例如:shell
>>> first_dict = {"abc":456,456:"hello",("love","python"):"loving"}數組
字典訪問函數
將相應的鍵放入方括號裏做爲索引,例如:spa
>>> first_dict = {"abc":456,456:"hello",("love","python"):"loving"}索引
>>> first_dict["abc"]字符串
456get
字典修改it
能夠向字典添加新的鍵值對,修改鍵值,例如:table
>>> first_dict = {"abc":456,456:"hello",("love","python"):"loving"}
>>>first_dict
{456: 'hello', 'abc': 456, ('love', 'python'): 'loving'}
>>> first_dict["abc"] = 123 #修改
>>> first_dict
{456: 'hello', 'abc': 123, ('love', 'python'): 'loving'}
>>> first_dict["first"] = "time" #添加
>>> first_dict
{456: 'hello', 'abc': 123, 'first': 'time', ('love', 'python'): 'loving'}
字典刪除
刪除單一元素、清空字典、刪除整個字典,例如:
>>> test_dict = {"name" : "yangyang","age":26,"class":"first"}
>>> del test_dict["class"] #刪除單一元素
>>> test_dict
{'age': 26, 'name': 'yangyang'}
>>> first_dict.clear() #清空字典
>>> first_dict
{}
>>> del test_dict #刪除整個字典
>>> test_dict
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
test_dict
NameError: name 'test_dict' is not defined
字典函數
語法 | 描述 | 參數 | 返回 | 實例 |
cmp(dict1,dict2) | 比較兩個字典元素 | dict1--比較字典 dict2--比較字典 |
dict1 > dict2:1 dict1 < dict2:-1 dict1 == dict2:0 |
>>> dict1 = {"name" : "Zara","age" : 7} |
len(dict) | 計算字典元素個數,即鍵總和 | dict--需計算元素個數的字典 | 返回字典的元素個數 | >>> dict1 = {"name":"lulu","age":7} |
str(dict) | 輸出字典可打印的字符串表示 | dict--須要轉換成字符串的字典 | 返回字典被轉換後的字典 | >>> dict1 = {"name" : "Zara","age" : 7} |
字典方法
語法 | 描述 | 參數 | 返回 | 實例 |
dict.clear() | 清除字典內全部元素 | 無 | 無 | >>> test_dict |
dict.get(key,default=None) | 返回指定鍵的值 | key--字典中要查找的鍵 |
返回指定鍵的值 | >>> test_dict = {"name" : "yangyang","age" : 27} |
dict.has_key(key) | 若是鍵在字典dict中返回true,不然則返回false | key--字典中要查找的鍵 | 若是鍵在字典dict中返回true,不然則返回false | >>> test_dict = {"name" : "yangyang","age" : 27} |
dict.items() | 以列表的返回可遍歷的(鍵,值)元祖數組 | 無 | 可遍歷的(鍵,值)元祖數組 | >>> test_dict = {"name" : "yangyang","age" : 27} |
dict.keys() | 以列表形式返回全部的鍵值 | 無 | 以列表形式返回全部的鍵值 | >>> test_dict = {"name" : "yangyang","age" : 27} |
dict.update(dict2) | 將dict2中值更新到dict | dict2--添加到指定dict裏的字典 | 無返回值 | >>>test_dict = {"name" : "yangyang","age" : 27} >>> update_dict = {"class" : "first"} >>> test_dict.update(update_dic) |
dict.values() | 返回字典中全部值 | 無 | 返回字典中全部值 | >>> test_dict = {"name" : "yangyang","age" : 27} >>> test_dict.values() |
pop() | 刪除字典中的一對鍵值 | 無 | 返回一個鍵值對(key,value) | >>> test_dict = {"name" : "yangyang","age" : 27,"class" : "first"}>>> test_dict.popitem()('age', 27) |