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

Posted wenyule

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python的6种基本数据类型--字典相关的知识,希望对你有一定的参考价值。

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

 

字典

字典的定义与特性

字典是Python语言中唯一的映射类型。
定义:{key1:value1,key2:value2}
1、键与值用冒号":"分开;
2、项与项用逗号","分开;
特性
1.key:value结构
2.key必须可hash、且必须为不可变数据类型、必须唯一(数字、字符串、元组)
3.value可存放任意多个值、可修改、可以不唯一
4.无序 
 

字典的创建与常见操作

字典的创建
 
# a.直接用 {} 创建,key:value对应
>>> skills = {"s1":"python","s2":"linux","s3":"html/css","s4":"JavaScript"}
>>> skills
{‘s1‘: ‘python‘, ‘s2‘: ‘linux‘, ‘s3‘: ‘html/css‘, ‘s4‘: ‘JavaScript‘}

# b.用dict转换
>>> skills_1 = dict(s1="python",s2="linux")
>>> skills_1
{‘s1‘: ‘python‘, ‘s2‘: ‘linux‘}
>>> skills_1 = dict("s1"="python","s2"="linux")                   # 不能这样创建,本身有歧义,前后都是两个字符串
SyntaxError: keyword can‘t be an expression
    
# 将本身就是字典转换成dict   
>>> skills_2 = dict({"s1":"python","s2":"linux"})
>>> skills_2
{‘s1‘: ‘python‘, ‘s2‘: ‘linux‘}

# 将形如key-value结构的转换为字典
>>> skills_3 = dict((["s1","python"],["s2","linux"]))
>>> skills_3
{‘s1‘: ‘python‘, ‘s2‘: ‘linux‘}
>>> skills_3 = dict([["s1","python"],["s2","linux"]])
>>> skills_3
{‘s1‘: ‘python‘, ‘s2‘: ‘linux‘}
>>> skills_3 = dict([("s1","python"),("s2","linux")])
>>> skills_3
{‘s1‘: ‘python‘, ‘s2‘: ‘linux‘}

# key 为元组的字典
>>> skills_3 = dict([[(1,2),"python"],[(21,21),"linux"]])
>>> skills_3
{(1, 2): ‘python‘, (21, 21): ‘linux‘}


给多个键赋相同的值
>>> dic = {}.fromkeys([‘s1‘,‘s2‘],[‘python‘,‘linux‘])
>>> dic
{‘s1‘: [‘python‘, ‘linux‘], ‘s2‘: [‘python‘, ‘linux‘]}
dic1 = {}.fromkeys([‘s1‘,‘s2‘],[‘python‘],[‘linux‘])        #最多两个变量,多了报错
Traceback (most recent call last):                          # 第二个变量是为共用的,当为可变类型时,可以修改添加,修改,
  File "<pyshell#71>", line 1, in <module>
    dic1 = {}.fromkeys([‘s1‘,‘s2‘],[‘python‘],[‘linux‘])
TypeError: fromkeys expected at most 2 arguments, got 3
>>> dic[‘s1‘].append(1)
>>> dic
{‘s1‘: [‘python‘, ‘linux‘, 1], ‘s2‘: [‘python‘, ‘linux‘, 1]}
>>> dic[‘s1‘].remove(‘python‘)
>>> dic
{‘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 修改
23 dic[key] = new_values    如果key在字典中存在,new_value将会替代原来的value值,不存在则创建
24 dic.update(dic2)         将字典dic2的键值对添加到字典dic中
25 
26 查看
27 dic[key]        返回字典中key对应的值,若key不存在字典中,则报错;
28 dict.get(key,default = None)        返回字典中key对应的值,若key不存在字典中,则返回default的值(default默认为None)
29 
30 
31 循环(3)
32 a.  for i in dic.keys()    等同于 for i in dic
33 >>> for k in skills.keys():print(k)
34 s1
35 s2
36 s3
37 s4
38 >>> for k in skills:print(k)
39 s1
40 s2
41 s3
42 s4
43 
44 b.  for k,v in dic.items()
45 
46 >>> for k,v in skills.items():print(k,v)
47 s1 python
48 s2 linux
49 s3 docker
50 s4 JavaScript
51 c.
52 >>> for k,v in enumerate(skills):print(k,v)
53 
54 0 s1
55 1 s2
56 2 s3
57 3 s4
58 >>> for k,v,j in enumerate(skills):print(k,v,j)
59 
60 Traceback (most recent call last):
61   File "<pyshell#48>", line 1, in <module>
62     for k,v,j in enumerate(skills):print(k,v,j)
63 ValueError: not enough values to unpack (expected 3, got 2)
64 
65 
66 长度
67 len(dic)

 

 

 

 

 

以上是关于python的6种基本数据类型--字典的主要内容,如果未能解决你的问题,请参考以下文章

python基本数据类型

《Python从小白到大牛》第6章 数据类型

《Python从小白到大牛》第6章 数据类型

第三天 PYTHON 基本数据类型 - 字典 - 布尔

Python3基础-基本数据类型之字典

python学习第5??天—2018.6.04基本数据类型(dict)