1、定义字典
>>> d1 = { //key-value的格式
"student1":"xiaoming",
"student2":"zhangsan",
"student3":"lisi"
}
2、查看
>>> print(d1["student1"]) //在已知有此key的情况下使用,在没有此key时会报错
xiaoming
>>> print(d1.get("student2")) //get方法不会报错
zhangsan
>>> print(d1.get("student1"))
None
3、修改key的值
>>> print(d1["student1"])
xiaoming
>>> d1["student1"] = "XiaoMing" //如果存在则修改,不存在则添加
>>> print(d1["student1"])
XiaoMing
4、删除
>>> del d1["student1"]
>>> print(d1)
{'student2': 'zhangsan', 'student3': 'lisi'}
5、判断字典里有没有某数据
>>> print("student1" in d1)
False
6、多级字典的嵌套
>>> d2 = {
"weibo":{
"guomao":["wilson","david","lucia"],
"bagou":["zhangsan","wangwu","lisi"]},
"xindongfang":{
"yuquan":["piter","alen","cc"],
"wukesong":["shenyang","lidong","wangwei"]}
}
7、修改嵌套菜单中的值
>>> print(d2["weibo"]["guomao"])
['wilson', 'david', 'lucia'] //修改之前
>>> d2["weibo"]["guomao"][1] = "大卫"
>>> print(d2["weibo"]["guomao"])
['wilson', '大卫', 'lucia'] //修改之后
8、打印字典中的所有值
>>> print(d2.values())
9、打印字典中所有的key
>>> print(d2.keys())
10、如果字典中存在此键则返回,不存在则创建
>>> print(d2)
{'weibo': {'guomao': ['wilson', '大卫', 'lucia'], 'bagou': ['zhangsan', 'wangwu', 'lisi']}, 'xindongfang': {'yuquan': ['piter', 'alen', 'cc'], 'wukesong': ['shenyang', 'lidong', 'wangwei']}}
>>> d2.setdefault("weibo",{"xinhua":["aa","bb","cc"]})
{'guomao': ['wilson', '大卫', 'lucia'], 'bagou': ['zhangsan', 'wangwu', 'lisi']}
>>> d2.setdefault("yingfu",{"xinhua":["aa","bb","cc"]})
{'xinhua': ['aa', 'bb', 'cc']}
>>> print(d2)
{'weibo': {'guomao': ['wilson', '大卫', 'lucia'], 'bagou': ['zhangsan', 'wangwu', 'lisi']}, 'xindongfang': {'yuquan': ['piter', 'alen', 'cc'], 'wukesong': ['shenyang', 'lidong', 'wangwei']}, 'yingfu': {'xinhua': ['aa', 'bb', 'cc']}}
11、合并两个字典,如果字典中有相同的key则更新,没有则添加
>>> d1
{'student2': 'zhangsan', 'student3': 'lisi'}
>>> d3 = {"student2":"AAAA","BBBBB":"CCCCC",1:2}
>>> d1.update(d3)
>>> print(d1)
{'student2': 'AAAA', 'student3': 'lisi', 'BBBBB': 'CCCCC', 1: 2}
12、把字典转换成列表
>>> print(d1.items())
dict_items([('student2', 'AAAA'), ('student3', 'lisi'), ('BBBBB', 'CCCCC'), (1, 2)])
可以循环打印
>>> for k,v in d1.items():
... print(k,v)
...
student2 AAAA
student3 lisi
BBBBB CCCCC
1 2
13、字典的循环
>>> for i in d1:
... print(i) //只打印key
...
student2
student3
BBBBB
1
>>> for i in d1:
... print(i,d1[i]) //把i当做key传入到字典中查询
...
student2 AAAA
student3 lisi
BBBBB CCCCC
1 2
14、for k,v in d1.items():和for i in d1:print(i,d1[i])的区别
第二种方式比较高效,因为第一种方式先把字典转换为列表,在数据量大的情况下,会导致资源的浪费。
原文地址:http://blog.51cto.com/12730062/2087605