使用花括号,并有key:value键值对,key必须是不可变对象
dic = {'a':2,'c':1,'b':3}
print dic
print (dic.items()) #items方法将字典转换为元组列表
L = sorted(dic.items(),key = lambda x:x[0],reverse = True)
print L
结果如下:
{'a': 2, 'c': 1, 'b': 3}
[('a', 2), ('c', 1), ('b', 3)]
[('c', 1), ('b', 3), ('a', 2)]
seq = ("baidu","huawei","tencent");
dict = dict.fromkeys(seq) #创建一个新的字典,但是没有初始化值,则默认为None
print "新的字典为:%s" % str(dict)
dict = dict.fromkeys(seq, 10) # 创建字典,并给键值一个初始化值
print "新的字典为:%s" % str(dict)
dict = {"名字":"pax","年龄":17,"Name":"baidu"}
print "dict:",dict["名字"]
del dict["名字"] #删除字典元素
print "dict:",dict
dict["年龄"] = 20 #修改字典元素
print "dict:",dict
dict["address"] = "road" #增加字典元素
print "dict:",dict
dict["电话"] = "0755" #增加键值
print "dict:",dict
'名字'in dict
dict.get('名字')