博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python字典 (dict)
阅读量:4561 次
发布时间:2019-06-08

本文共 8212 字,大约阅读时间需要 27 分钟。

作者博文地址:http://www.cnblogs.com/spiritman/

字典是Python语言中唯一的映射类型。字典对象是可变的,它是一个容器类型,支持异构、任意嵌套。

创建字典

  语法:{key1:val1,key2:val2,.....}

  dict1 = {}      #创建空字典

  dict2 = {'n1':'liush','n2':'spirit','n3':'tester'}

  使用函数dict创建字典

1 >>>D = dict(name='spititman',age=28,gender='M')2 >>>print D3 {
'gender': 'M', 'age': 28, 'name': 'spititman'}

  使用zip和dict创建字典

1 zip语法: 2     zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)] 3 实例展示: 4     >>>L = zip('xyz','123') 5     >>>print L 6     [('x', '1'), ('y', '2'), ('z', '3')] 7  8     >>>L = zip('xyz','123','abc') 9     >>>print L10     [('x', '1', 'a'), ('y', '2', 'b'), ('z', '3', 'c')]11 ################################################################################12 >>>D = dict(zip('xyz','123'))13 >>>print D14 {
'y': '2', 'x': '1', 'z': '3'}15 16 >>>D = dict(zip('xyz','123','abc'))17 >>>print D18 ValueError: dictionary update sequence element #0 has length 3; 2 is required

 

字典常用操作及实例展示

  可以使用dir(dict)查看字典支持的操作方法

clear

  功能:清空字典所有元素

  语法:D.clear() -> None.  Remove all items from D

  实例展示:

1 >>>D = {
'n1':'liush','n2':'spirit','n3':'tester'}2 >>>D.clear()3 >>>print D4 {}

copy

  功能:浅复制字典。

  语法:D.copy() -> a shallow copy of D

  实例展示:

1 >>>D = {
'n1':'liush','n2':'spirit','n3':'tester'}2 >>>id(D)3 1403882119112084 >>>D1 = D.copy()5 >>>print D16 {
'n1': 'liush', 'n2': 'spirit', 'n3': 'tester'}7 >>>id(D1)8 140388110074776

fromkeys

  功能:用于创建一个新字典,以序列S中的元素作为字典的键,v为新字典中所有键对应的初始值,默认为none。

  语法:dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.v defaults to None

  实例展示:

1 >>>L = ['spirit','man','liush']2 >>>D_L = dict.fromkeys(L)3 >>>print D_L4 {
'liush': None, 'spirit': None, 'man': None}5 ########################################################6 >>>D_L = dict.fromkeys(L,'test')7 >>>print D_L8 {
'liush': 'test', 'spirit': 'test', 'man': 'test'}

get

  功能:获取指定键的值

  语法:D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None

  实例展示:

1 >>>D = {
'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'} 2 >>>D1 = D.get('n4') 3 >>>print D1 4 none #n4不在字典D中,返回默认值none 5 ########################################################## 6 >>>D2 = D.get('n4','check') 7 >>>print D2 8 check #n4不在字典D中,返回指定值check 9 ##########################################################10 >>>D3 = D.get('n2')11 >>>print D312 spirit #n2在字典D中,返回n2对应的值13 ##########################################################14 >>>D4 = D.get('n2','check')15 >>>print D416 spirit #n2在字典D中,指定值无效,依然返回其对应值

has_key

  功能:判断字典中是否存在指定键

  语法:D.has_key(k) -> True if D has a key k, else False

  实例展示:

1 >>>D = {
'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'}2 >>>D.has_key('n4')3 False4 ######################################################5 >>>D.has_key('n2')6 True

items

  功能:返回以字典中的键值对组成的元组作为元素的列表

  语法:D.items() ->  list of D's (key, value) pairs, as 2-tuples

  实例展示:

1 >>>D = {
'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'}2 >>>L = D.items()3 >>>print L4 [('n1', 'liushuai'), ('n2', 'spirit'), ('n3', 'tester')]5 >>>type(L)6

iteritems

  功能:对以字典中的键值对组成的元组进行迭代,可用于for循环

  语法:D.iteritems() -> an iterator over the (key, value) items of D

  实例展示:

1 >>>D = {
'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'} 2 >>>L = D.iteritems() 3 >>>print L 4
#生成一个迭代器地址 5 >>>L.next()              #开始迭代 6 ('n1', 'liushuai') 7 >>>L.next() 8 ('n2', 'spirit') 9 >>>L.next()10 ('n3', 'tester')11 >>>L.next()              #迭代完成后报错12 Traceback (most recent call last):13 File "
", line 1, in
14 StopIteration15 #########################################################################16 >>>for i in D.iteritems():      #使用for循环遍历17 ... print i 18 ...19 ('n1', 'liushuai')20 ('n2', 'spirit')21 ('n3', 'tester')

iterkeys

  功能:对字典中的键进行迭代(遍历)

  语法:D.iterkeys() -> an iterator over the keys of D

  实例展示:

1 >>>D = {
'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'} 2 >>>L = D.itervalues() 3 >>>print L 4
5 >>>L.next() 6 'n1' 7 >>>L.next() 8 'n2' 9 >>>L.next()10 'n3'11 >>>L.next()12 Traceback (most recent call last):13 File "
", line 1, in
14 StopIteration15 #############################################################16 >>>for i in D.iterkeys():17 ... print i18 ...19 n120 n221 n3

 

itervalues

  功能:对字典中的键进行迭代(遍历)

  语法:D.itervalues() -> an iterator over the values of D

  实例展示:

1 >>>D = {
'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'} 2 >>>L = D.itervalues() 3 >>>print L 4
5 >>>L.next() 6 'liushuai' 7 >>>L.next() 8 'spirit' 9 >>>L.next()10 'tester'11 >>>L.next()12 Traceback (most recent call last):13 File "
", line 1, in
14 StopIteration15 #############################################################16 >>>for i in D.itervalues():17 ... print i18 ...19 liushuai20 spirit21 tester

keys

  功能:以列表的形式返回所有键

  语法:D.keys() -> list of D's keys

  实例展示:

1 >>>D = {
'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'}2 >>>L = D.keys()3 >>>print L4 ['n1','n2','n3']

pop

  功能:从字典中删除指定的键,返回其对应的值。

  语法:D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised

  实例展示:

1 >>>D = {
'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'} 2 >>>D.pop('n4')        #指定的键不存在,返回报错 3 Traceback (most recent call last): 4 File "
", line 1, in
5 ################################################## 6 KeyError: 'n4'        #指定的键不存在,返回指定的值 7 >>>D.pop('n4','check') 8 'check' 9 ##################################################10 >>>D.pop('n2')     #指定的键存在,返回其对应值11 'spirit'12 ##################################################13 >>>D.pop('n3','check')   #指定的键存在,指定值无效,依然返回其对应值14 'tester'15 ##################################################

popitem

  功能:随机删除字典的键值对并以元组的形式返回

  语法:D.popitem() -> (k, v), remove and return some (key, value) pair as a

    2-tuple; but raise KeyError if D is empty.

  实例展示:

1 >>>D = {
'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'} 2 >>>D.popitem() 3 ('n1', 'liushuai') 4 >>>D.popitem() 5 ('n2', 'spirit') 6 >>>D.popitem() 7 ('n3', 'tester') 8 >>>D.popitem() #当字典为空时,抛出异常。 Traceback (most recent call last): File "
", line 1, in
KeyError: 'popitem(): dictionary is empty'

setdefault

  功能:查找键值。若键不在字典中,将会添加键并将值设定为默认值

  语法:D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

  实例展示:

1 >>>D = {
'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'} 2 ##指定的键存在,则返回其对应的值,原字典不变 3 >>>D.setdefault('n2') 4 'spirit' 5 >>>print D 6 {
'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'} 7 ####################################################################### 8 ##指定的键不存在,则修改原字典,该键对应的值默认为none 9 >>>D.setdefault('n4')10 >>>print D11 {
'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester', 'n4': None}12 #######################################################################13 ##指定的键不存在,则修改原字典,该键对应的值为指定值14 >>>D.setdefault('n5','check')15 >>>print D16 {
'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester', 'n4': None, 'n5': 'check'}

update

  功能:以字典或迭代器更新原字典

  语法: D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.

        If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
        If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
        In either case, this is followed by: for k in F: D[k] = F[k]

  实例展示:

1 >>>D = {
'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'} 2 >>>D1 = {
'n1':'liush','n4':'Jerry'} 3 >>>D2 = {1:'IT',2:'SALE'} 4 #键相同时,则其对应的原字典的值将被覆盖 5 >>>D.update(D1) 6 {
'n1': 'liush', 'n2': 'spirit', 'n3': 'tester', 'n4': 'Jerry'} 7 #################################################### 8 #键不同时,则追加 9 >>>D.update(D2)10 {1: 'IT', 2: 'SALE', 'n1': 'liush', 'n2': 'spirit', 'n3': 'tester', 'n4': 'Jerry'}

values

  功能:以列表的形式返回所有值

  语法:D.values() -> list of D's values

  实例展示:

1 >>>D = {
'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'}2 >>>L = D.values()3 >>>print L4 ['liushuai', 'spirit', 'tester']

作者博文地址:http://www.cnblogs.com/spiritman/

转载于:https://www.cnblogs.com/spiritman/p/5142559.html

你可能感兴趣的文章
软件安装
查看>>
黑盒测试实践—第四天
查看>>
luogu P4448 [AHOI2018初中组]球球的排列
查看>>
[No000016C]做企业分析的三个重要工具
查看>>
win7每天出现taskeng.exe进程的解决方案
查看>>
c++:资源管理(RAII)、new/delete的使用、接口设计与声明、swap函数
查看>>
React Children
查看>>
大数据等最核心的关键技术:32个算法
查看>>
Maven多模块项目搭建
查看>>
redis列表list
查看>>
雷林鹏分享: C# 简介
查看>>
ORA-12505: TNS: 监听程序当前无法识别连接描述符中所给出的SID等错误解决方法
查看>>
实用类-<Math类常用>
查看>>
构建之法阅读笔记之四
查看>>
10.15习题2
查看>>
Windows Server 2008 R2 备份与恢复详细实例
查看>>
Ubuntu上kubeadm安装Kubernetes集群
查看>>
关于java学习中的一些易错点(基础篇)
查看>>
MFC的多国语言界面的实现
查看>>
四则运算个人项目 最终版
查看>>