字典键是唯一的,但值则不是
一个简单的字典 dict = {"guo":"1106","tang":"0809","xie":"0924"} dict1 = {"abc":456} dic2 = {12:123,98.6:33}
访问字典的值 d = dic["guo"] 输出结果:1106 修改字典 dic["guo"]="1107" #把1106的值改为1107 删除字典元素 dict = {"guo",1106,"zhu":0724,"tang":0809,"xie":"0924"} del dict["guo"] #删除guo del dict #删除字典 dic.clear()#清空字典内容
字典的特性
字典的键不允许出现两次,如果出现两次,会记住最后面一个 例: dict = {"guo":123,"tang":456,"guo":789} print dict["guo"] 输出结果:789 键不可变,所以可以是数字,字符串,元组。列表就不可以 例:
dict = {["name"]:"guo","Age":7} print dict["name"]#这样会错误提示TypeError: unhashable type: 'list'
字典内置函数以及方法
len(dict)#计算字典的键的总个数 例: dict = {"guo":123,"tang":456,"xie":789} print len(dict) 输出结果:3
str(dict)可以以字符串的形式打印 dict = {"guo":123,"tang":456,"xie":789} print "this is %s"%str(dict) 输出结果:this is {'tang': 456, 'guo': 123, 'xie': 789}
type(dict)查看类型
dict = {"guo":123,"tang":456,"xie":789} print type(dict) 输出结果:<type 'dict'>
get()方法 dict = {"guo":123,"tang":456,"xie":789} print dict.get(guo)#指定返回guo的值 输出结果:123 print dict.get("gg")#当没有gg这个键时,返回None 输出结果: None
dic.items() dict = {"guo":123,"tang":456,"xie":789} print dict.items() 输出结果: [('tang', 456), ('guo', 123), ('xie', 789)]#以列表形式返回键和值 for key,value in dict.items(): print key,value 输出结果: tang 456 guo 123 xie 789
dict.values()# 返回字典中的所有值,以列表形式返回 dict = {"guo":123,"tang":456,"xie":789} print dict.values() 输出结果: [456, 123, 789]