html5 手机网站模版,黄金网站app免费视频下载,广告资源对接平台,如何用html做网站头像Python字典是另一种可变容器模型(无序)#xff0c;且可存储任意类型对象#xff0c;如字符串、数字、元组等其他容器模型。本文章主要介绍Python中字典(Dict)的详解操作方法,包含创建、访问、删除、其它操作等,需要的朋友可以参考下。
字典由键和对应值成对组成。字典也被称作…Python字典是另一种可变容器模型(无序)且可存储任意类型对象如字符串、数字、元组等其他容器模型。本文章主要介绍Python中字典(Dict)的详解操作方法,包含创建、访问、删除、其它操作等,需要的朋友可以参考下。
字典由键和对应值成对组成。字典也被称作关联数组或哈希表。基本语法如下
1.创建字典
1
2
3
4
5
6
7dict {ob1:computer,ob2:mouse,ob3:printer}
技巧
字典中包含列表dict{yangrong:[23,IT],xiaohei:[22,dota]}
字典中包含字典dict{yangrong:{age:23,job:IT},xiaohei:{age:22,job:dota}}
注意
每个键与值用冒号隔开:每对用逗号每对用逗号分割整体放在花括号中{}。
键必须独一无二但值则不必。
2.访问字典里的值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
dict {ob1:computer,ob2:mouse,ob3:printer}
print(dict[ob1])
computer
如果用字典里没有的键访问数据会输出错误如下
print(dict[ob4])
Traceback (most recent call last):
File , line1,in
print(dict[ob4])
访问所有值dict1 {ob1:computer,ob2:mouse,ob3:printer}
for keyin dict1:
print(key,dict1[key])
ob3 printer
ob2 mouse
ob1 computer
3.修改字典
1
2
3
4
dict {ob1:computer,ob2:mouse,ob3:printer}
dict[ob1]book
print(dict)
{ob3:printer,ob2:mouse,ob1:book}
4.删除字典
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
能删单一的元素
dict {ob1:computer,ob2:mouse,ob3:printer}
del dict[ob1]
print(dict)
{ob3:printer,ob2:mouse}
删除字典中所有元素dict1{ob1:computer,ob2:mouse,ob1:printer}dict1.clear()
print(dict1)
{}
删除整个字典删除后访问字典会抛出异常。dict1 {ob1:computer,ob2:mouse,ob3:printer}
del dict1
print(dict1)
Traceback (most recent call last):
File , line1,in
print(dict1)
NameError: namedict1 is not defined
5.更新字典
1
2
3
4
5
6
update()方法可以用来将一个字典的内容添加到另外一个字典中dict1 {ob1:computer,ob2:mouse}dict2{ob3:printer}dict1.update(dict2)
print(dict1)
{ob3:printer,ob2:mouse,ob1:computer}
6.映射类型相关的函数
1
2
3
4
5
6
7
8
9
10
dict(x1, y2)
{y:2,x:1}dict8 dict(x1, y2)dict8
{y:2,x:1}dict9 dict(**dict8)dict9
{y:2,x:1}
dict9 dict8.copy()
7.字典键的特性
1
2
3
4
5
6
7
8
9
10
11
12
13
字典值可以没有限制地取任何python对象既可以是标准的对象也可以是用户定义的但键不行。
两个重要的点需要记住
1不允许同一个键出现两次。创建时如果同一个键被赋值两次后一个值会被记住dict1{ob1:computer,ob2:mouse,ob1:printer}
print(dict1)
{ob2:mouse,ob1:printer}
2键必须不可变所以可以用数字符串或元组充当用列表就不行dict1 {[ob1]:computer,ob2:mouse,ob3:printer}
Traceback (most recent call last):
File , line1,in
dict1 {[ob1]:computer,ob2:mouse,ob3:printer}
TypeError: unhashabletype:list
8.字典内置函数方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Python字典包含了以下内置函数
1、cmp(dict1, dict2)比较两个字典元素。(python3后不可用)
2、len(dict)计算字典元素个数即键的总数。
3、str(dict)输出字典可打印的字符串。
4、type(variable)返回输入的变量类型如果变量是字典就返回字典类型。
Python字典包含了以下内置方法
1、radiansdict.clear()删除字典内所有元素
2、radiansdict.copy()返回一个字典的浅复制
3、radiansdict.fromkeys()创建一个新字典以序列seq中元素做字典的键val为字典所有键对应的初始值
4、radiansdict.get(key, defaultNone)返回指定键的值如果值不在字典中返回default值
5、radiansdict.has_key(key)如果键在字典dict里返回true否则返回false
6、radiansdict.items()以列表返回可遍历的(键, 值) 元组数组
7、radiansdict.keys()以列表返回一个字典所有的键
8、radiansdict.setdefault(key, defaultNone)和get()类似, 但如果键不已经存在于字典中将会添加键并将值设为default
9、radiansdict.update(dict2)把字典dict2的键/值对更新到dict里
10、radiansdict.values()以列表返回字典中的所有值
以上这篇python字典的常用操作方法小结就是小编分享给大家的全部内容了希望能给大家一个参考也希望大家多多支持服务器之家。