一、【建立字典】 自定义(建立新字典)一个字典并赋初值
#-*-coding:utf-8-*- dict = { 'name':"xiaohua", "age":19,"weight":46,"name":"xianliu" }原则上同一个字典中,禁止出现相同的“键”,如果出现,也未尝不可,但是会输出后面的的值 键必须不可变,所以可以用 数字、字符串或者元祖来充当,但就是不能用“列表”,一定要记住。
二、【访问操作】 此打印输出操作,就是在 对字典 “值” 进行访问,[]内只准使用“键”,不可使用下标:
#-*-coding:utf-8-*- dict = { 'name':"xiaohua", "age":19,"weight":46,"name":"xianliu" } print dict['name'] print dict["age"] #错误格式: #print dict[0]代码运行结果:
xianliu 19三、【修改字典】 这种操作 与 整型数的赋值是一样的,在这里,我们有一种特别高大上的技术名称: 修改字典
dict = { 'name':"xiaohua", "age":19,"weight":46,"name":"xianliu" } dict["name"] = "hahaha" print dict代码运行结果:
{'age': 19, 'name': 'hahaha', 'weight': 46}四、【删除字典】 与删除有关的种种操作,没错,就是不乏这种操作,只是你不知道而已 1、删除字典的 某个键 ,比如:’name’
dict = { 'name':"xiaohua", "age":19,"weight":46,"name":"xianliu" } del dict['name'] print dict代码运行结果:
{'age': 19, 'weight': 46}2、清空字典所有内容
dict.clear() #输出的内容包括字典的{}的大括号,就是说,清空的是字典的内容,而不包含{} print dict代码运行结果:
{}3、用来显示出字典的被删除“键”的 “值”,就用dict.pop(“指定键”),输出“该键”对应的 “值”
dict = { "1":"hello","2":"world","3":"nihao","4":"shijie" } print dict.pop("2") print dict代码运行结果:
world {'1': 'hello', '3': 'nihao', '4': 'shijie'}4、删除整个字典,这个就比狠了,用最简单的操作,做最狠的抹杀;
del dict print dict代码运行结果:
<type 'dict'>5、随机删除某个键极其对应的值(这个岂不是更狠,更毒。。。):
site= {'name': '菜鸟教程', 'alexa': 10000, 'url': 'www.runoob.com'} pop_obj=site.popitem() print(pop_obj) print(site)代码运行结果:
('url', 'www.runoob.com') {'alexa': 10000, 'name': '\xe8\x8f\x9c\xe9\xb8\x9f\xe6\x95\x99\xe7\xa8\x8b'}五、【查证变量类型】当不知道一个变量类型的时候,我们求助于python自身的内置函数,type(位置类型变量)
print type(dict)代码运行结果:
<type 'type'>六、【字典内置函数&方法】
dict1 = {"name":"nihao","weight":454} #1、求字典的:元素个数(求键的个数): print len (dict1) #2、字典的字符串表示法,这个不重要,但是下面咱们要说到 字典的复制函数要用,所以就提到这种操作了: dict = {'Name': 'Zara', 'Age': 7}; print "Equivalent String : %s" % str (dict) #3、复制函数(雷死人的操作,哈哈哈) dict1 = {'Name': 'Zara', 'Age': 7}; dict2 = dict1.copy() print "New Dictinary : %s" % str(dict2) #4、返回指定“键”的值 print dict2.get("Name") #5、以列表返回可遍历的(键、值)元组数组 #dict.items() dict = {'Google': 'www.google.com', 'Runoob': 'www.runoob.com', 'taobao': 'www.taobao.com'} print "字典值 : %s" % dict.items() # 遍历字典列表 for key,values in dict.items(): print key,values #6、更新字典(是把括号内的内容添加到待更新的字典中,添加,待更新字典中的原有内容并不减少): dict = {'Name': 'Zara', 'Age': 7} dict2 = {'Sex': 'female' } dict.update(dict2) print ("Value : %s"%str(dict)) #7、遍历“键”和“值”: #key、value dict = {'Name': 'Zara', 'Age': 7} print "Value : %s" % dict.keys() #遍历“键”: for key in dict.keys(): print key #遍历“值”: for value in dict.values(): print value第六部分、全部代码运行结果:
2 Equivalent String : {'Age': 7, 'Name': 'Zara'} New Dictinary : {'Age': 7, 'Name': 'Zara'} Zara 字典值 : [('Google', 'www.google.com'), ('taobao', 'www.taobao.com'), ('Runoob', 'www.runoob.com')] Google www.google.com taobao www.taobao.com Runoob www.runoob.com Value : {'Age': 7, 'Name': 'Zara', 'Sex': 'female'} Value : ['Age', 'Name'] Age Name 7 Zara