组合数据类型(字典)
1,创建字典
a,直接创建
dic = {'a':1,'b':2,'c':3} print (dic) >>>{'b': 2, 'a': 1, 'c': 3}
b,函数创建
dic= dict(a=1,b=2,c=3) print (dic) >>>{'b': 2, 'c': 3, 'a': 1}
2,基本操作
a,判断
dic1 = {'a':1,'b':2,'c':3} print ('a' in dic1) # 此处只能判断key print (1 in dic1) >>>True False
b,追加
dic = {'a':1,'b':2,'c':3} dic['d'] = 4 print (dic) >>>{'c': 3, 'a': 1, 'b': 2, 'd': 4}
c,修改
dic = {'a':1,'b':2,'c':3} dic['a'] = 4 print (dic) >>>{'c': 3, 'a': 4, 'b': 2}
d,删除
dic = {'a':1,'b':2,'c':3} del dic['a'] print (dic) >>>{'c': 3, 'b': 2}
3,常用功能
a,追加
dic1 = {'a':1,'b':2,'c':3} dic2 = {'d':4} dic3 = dic2.update(dic1) # 将字典dic1合并到字典dic2中去 print (dic1) print (dic2) >>>{'b': 2, 'a': 1, 'c': 3} {'d': 4, 'a': 1, 'b': 2, 'c': 3}
c,复制
dic1 = {'a':1,'b':2,'c':3} dic2 = {'d':4} dic3 = dic1.copy() dic1.update(dic2) # 注意不能将追加后的字典直接赋值给变量dic4=dic1.update(dic2) print (dic3) print (dic1)
d,清空
dic = {'a':1,'b':2,'c':3} dic.clear() # 清空字典 print (dic) >>>{}
4,访问字典
a,获取健key对应值value
dic = {'a':1,'b':2,'c':3} print (dic.get('a')) >>>1
b,获取所有健key
dic = {'a':1,'b':2,'c':3} print (dic.keys()) >>>dict_keys(['a', 'b', 'c'])
c,获取所有值value
dic = {'a':1,'b':2,'c':3} print (dic.values() >>>dict_values([1, 2, 3])
d,获取健值对items
dic = {'a':1,'b':2,'c':3} print (dic.items()) >>>dict_items([('a', 1), ('b', 2), ('c', 3)])
5,遍历字典
a,遍历所有健key
dic = {'a':1,'b':2,'c':3} for key in dic.keys(): print (key) >>>b a c
b,遍历所有值values
dic = {'a':1,'b':2,'c':3} for value in dic.values(): print (value) >>>2 1 3
c,遍历所有健值对items
dic = {'a':1,'b':2,'c':3} for (k,v) in dic.items(): print (k,v) >>>a 1 b 2 c 3