18、python基础学习-字典
1 #!/usr/bin/env python
2 #__author: hlc
3 #date: 2019/5/26
4 #字典是python中唯一的映射类型,采用键值对(key-value)的形式进行存储,python对key进行哈希函数运算,根据结果决定value的存储地址,所以字典是无序存储的,且key必须是可哈希的。可哈希表示key必须是不可变类型,如:数字、字符串、元祖。
5
6 #字典的两种创建方法
7 # dic = {"asd":"123","asgd":456}
8 # print(dic)
9 #
10 # a = dict(((1,4),(5,7))) #工厂模式
11 # print(a)
12
13 #增加
14 # dict1 = {}
15 # dict1["asd"]=123 #如果健存在,会进行覆盖,不存在会添加
16 # print(dict1) #{'asd': 123}
17 # dict1.setdefault("qwe",3245) #如果健存在,不会进行覆盖,不存在会添加,都会返回对应的值
18 # print(dict1) #{'asd': 123, 'qwe': 3245}
19
20 #查找(通过键查找)
21 # dic2 = {"asd":"123","asgd":456,"erqw":"sdfdsg"}
22 # print(dic2["asd"]) #123
23 # print(dic2.keys()) #获取字典中所有键,dict_keys(['asd', 'asgd', 'erqw'])
24 # print(list(dic2.keys())) #转换成列表,['asd', 'asgd', 'erqw']
25 # print(dic2.values()) #获取字典中所有的值,dict_values(['123', 456, 'sdfdsg'])
26 # print(list(dic2.values())) #转换成列表,['123', 456, 'sdfdsg']
27 # print(dic2.items()) #获取字典中的所有值,dict_items([('asd', '123'), ('asgd', 456), ('erqw', 'sdfdsg')])
28 # print(list(dic2.items())) #转换成列表,[('asd', '123'), ('asgd', 456), ('erqw', 'sdfdsg')]
29
30 #修改
31 # dic2 = {"asd":"123","asgd":456,"erqw":"sdfdsg"}
32 # dic2["asd"]=789
33 # print(dic2) #{'asd': 789, 'asgd': 456, 'erqw': 'sdfdsg'}
34 # dic3 = {"a":1,"b":2,"asd":3}
35 # dic2.update(dic3) #将dict3添加到dict2中,如果键存在,会进行更新
36 # print(dic2) #{'asd': 3, 'asgd': 456, 'erqw': 'sdfdsg', 'a': 1, 'b': 2}
37
38 #删除
39 # dic2 = {"asd":"123","asgd":456,"erqw":"sdfdsg"}
40 # del dic2["asgd"] #删除对应的键值对
41 # print(dic2) #{'asd': '123', 'erqw': 'sdfdsg'}
42 # dic3 = dic2.pop("asd") #删除对应的键值对,并将对应的内容返回
43 # print(dic3) # 123
44 # dic2 = {"asd":"123","asgd":456,"erqw":"sdfdsg"}
45 # dic4 = dic2.popitem() #随机删除,并将对应的键值以元祖的方式返回
46 # print(dic4) # ('erqw', 'sdfdsg')
47 # dic2.clear() #将字典中的内容进行清空
48 # print(dic2) # {}
49 #del dic2 #删除整个字典
50
51 #其他操作
52 # a = ["a","b","c","d","e"]
53 # dic3 = dict.fromkeys(a,"test") #将列表中的元素作为键,test作为值生成字典
54 # print(dic3) #{'a': 'test', 'b': 'test', 'c': 'test', 'd': 'test', 'e': 'test'}
55
56 #排序
57 # dic5 = {4:"asdf",2:"dfgk",8:"asdfg"}
58 # dic6 = sorted(dict.items(dic5)) # 按键排序,以列表的形式返回键值对,[(2, 'dfgk'), (4, 'asdf'), (8, 'asdfg')]
59 # dic6 = sorted(dict.values(dic5)) # 按值排序,以列表的形式返回值,['asdf', 'asdfg', 'dfgk']
60 # dic6 = sorted(dic5) # 按键排序,以列表的形式返回键,[2, 4, 8]
61 # print(dic6)
62
63 #字典的遍历
64 # dic5 = {4:"asdf",2:"dfgk",8:"asdfg"}
65 # for i in dic5 :
66 # print(i,dic5[i]) #通过键进行遍历 效率最高
67 # 4 asdf
68 # 2 dfgk
69 # 8 asdfg
70 # for i in dic5.items() :
71 # print(i) # 通过字典的内建方法进行变量
72 # (4, 'asdf')
73 # (2, 'dfgk')
74 # (8, 'asdfg')
75 # for i,v in dic5.items() :
76 # print(i,v) # 通过两个值进行接受
77 # 4 asdf
78 # 2 dfgk
79 # 8 asdfg