python的6种基本数据类型--字典

python的6种基本数据类型--字典

 

字典

字典的定义与特性

字典是Python语言中唯一的映射类型。
定义:{key1:value1,key2:value2}
  1、键与值用冒号":"分开;
  2、项与项用逗号","分开;
特性
  1.key:value结构
  2.key必须可hash、且必须为不可变数据类型、必须唯一(数字、字符串、元组)
  3.value可存放任意多个值、可修改、可以不唯一
  4.无序 
 
 
字典的创建与常见操作
字典的创建
 
 1 # a.直接用 {} 创建,key:value对应
 2 >>> skills = {"s1":"python","s2":"linux","s3":"html/css","s4":"JavaScript"}
 3 >>> skills
 4 {'s1': 'python', 's2': 'linux', 's3': 'html/css', 's4': 'JavaScript'}
 5 
 6 # b.用dict转换
 7 >>> skills_1 = dict(s1="python",s2="linux")
 8 >>> skills_1
 9 {'s1': 'python', 's2': 'linux'}
10 >>> skills_1 = dict("s1"="python","s2"="linux")                   # 不能这样创建,本身有歧义,前后都是两个字符串
11 SyntaxError: keyword can't be an expression
12     
13 # 将本身就是字典转换成dict   
14 >>> skills_2 = dict({"s1":"python","s2":"linux"})
15 >>> skills_2
16 {'s1': 'python', 's2': 'linux'}
17 
18 # 将形如key-value结构的转换为字典
19 >>> skills_3 = dict((["s1","python"],["s2","linux"]))
20 >>> skills_3
21 {'s1': 'python', 's2': 'linux'}
22 >>> skills_3 = dict([["s1","python"],["s2","linux"]])
23 >>> skills_3
24 {'s1': 'python', 's2': 'linux'}
25 >>> skills_3 = dict([("s1","python"),("s2","linux")])
26 >>> skills_3
27 {'s1': 'python', 's2': 'linux'}
28 
29 # key 为元组的字典
30 >>> skills_3 = dict([[(1,2),"python"],[(21,21),"linux"]])
31 >>> skills_3
32 {(1, 2): 'python', (21, 21): 'linux'}
33 
34 
35 给多个键赋相同的值
36 >>> dic = {}.fromkeys(['s1','s2'],['python','linux'])
37 >>> dic
38 {'s1': ['python', 'linux'], 's2': ['python', 'linux']}
39 dic1 = {}.fromkeys(['s1','s2'],['python'],['linux'])        #最多两个变量,多了报错
40 Traceback (most recent call last):                          # 第二个变量是为共用的,当为可变类型时,可以修改添加,修改,
41   File "<pyshell#71>", line 1, in <module>
42     dic1 = {}.fromkeys(['s1','s2'],['python'],['linux'])
43 TypeError: fromkeys expected at most 2 arguments, got 3
44 >>> dic['s1'].append(1)
45 >>> dic
46 {'s1': ['python', 'linux', 1], 's2': ['python', 'linux', 1]}
47 >>> dic['s1'].remove('python')
48 >>> dic
49 {'s1': ['linux', 1, 1], 's2': ['linux', 1, 1]}

 

字典的常见操作

 

 1 键、值、键值对
 2 dic.keys()       返回一个包含字典所有KEY的列表;
 3 dic.values()     返回一个包含字典所有value的列表;
 4 dic.items()      返回一个包含所有(键,值)元祖的列表;
 5 
 6 >>> skills
 7 {'s1': 'python', 's2': 'linux', 's3': 'html/css', 's4': 'JavaScript'}
 8 >>> skills.keys
 9 <built-in method keys of dict object at 0x00000209A130DCF0>
10 >>> skills.keys()
11 dict_keys(['s1', 's2', 's3', 's4'])
12 >>> skills.values()
13 dict_values(['python', 'linux', 'html/css', 'JavaScript'])
14 >>> skills.items()
15 dict_items([('s1', 'python'), ('s2', 'linux'), ('s3', 'html/css'), ('s4', 'JavaScript')])
16 
17 新增
18 dic['new_key'] = 'new_value'
19 dic.setdefault(key,None)    如果字典中不存在Key键,由 dic[key] = default 为它赋值,这里defalut=None,实际创建需要填value
20 
21 删除
22 dic.pop(key[,default]) 和get方法相似。如果字典中存在key,删除并返回key对应的vuale;如果key不存在,且没有给出default的值,则引发keyerror异常;
23 dic.clear() 删除字典中的所有项或元素;   
24 >>> skills.pop('s4')
25 'JavaScript'
26 >>> skills
27 {'s1': 'python', 's2': 'linux', 's3': 'docker'}
28 >>> skills
29 {}
30 
31 修改
32 dic['key'] = 'new_values'    如果key在字典中存在,'new_value'将会替代原来的value值,不存在则创建
33 dic.update(dic2)         将字典dic2的键值对添加到字典dic中
34 
35 查看
36 dic['key']        返回字典中key对应的值,若key不存在字典中,则报错;
37 dict.get(key,default = None)        返回字典中key对应的值,若key不存在字典中,则返回default的值(default默认为None)
38 
39 
40 循环(3)
41 a.  for i in dic.keys()    等同于 for i in dic
42 >>> for k in skills.keys():print(k)
43 s1
44 s2
45 s3
46 s4
47 >>> for k in skills:print(k)
48 s1
49 s2
50 s3
51 s4
52 
53 b.  for k,v in dic.items()
54 
55 >>> for k,v in skills.items():print(k,v)
56 s1 python
57 s2 linux
58 s3 docker
59 s4 JavaScript
60 c.
61 >>> for k,v in enumerate(skills):print(k,v)
62 
63 0 s1
64 1 s2
65 2 s3
66 3 s4
67 >>> for k,v,j in enumerate(skills):print(k,v,j)
68 
69 Traceback (most recent call last):
70   File "<pyshell#48>", line 1, in <module>
71     for k,v,j in enumerate(skills):print(k,v,j)
72 ValueError: not enough values to unpack (expected 3, got 2)
73 
74 
75 长度
76 len(dic)

 

 

 

 

 

 

 

posted @ 2018-04-29 19:55  前海渔文乐  阅读(1125)  评论(0编辑  收藏  举报