首页 > 编程知识 正文

python字典实现分析的简单介绍

时间:2023-12-28 11:56:48 阅读:327827 作者:OVDF

本文目录一览:

python3 如何解析多层嵌套字典,具体内容打开看

# 见 代码   ,代码粘贴上不带格式,按照图片用tab键调整一下,图片是核心部分

simple_dict = {

'Large_dict' : {'middle_dict1' : {'small_dict1' : 1 ,

'small_dict2' : 2},

'middle_dict2' : {'small_dict3' : 3 ,

'small_dict4' : 4,

'small_dict5':{'small_dict10' : 1 ,

'small_dict22' : 3},

},

}

}

# 需求分析: 从嵌套字典中,找到值为3的  路径关系

# 简化模型:从value为3的值 递归向上层的 key ,递归过程保存当前已经递归的路径和当前层

# 1.找到字典一共有多少层:

count = 0

path = ''# 设置路径的全局变量

result = []  # 记录结论

def get_count(dict_test):

global count  # 声明每次递归均是改变全局变量

global path  # 拼接档期啊你的路径

global result  # 记录结果

for i in dict_test:

if type(dict_test[i]).__name__ =='dict' :

# 如果是字典,则继续向下展开,即执行递归:

if count == 0:   # 增加判断 消除第一个 - 出现,逻辑问题

path = path  + i

else:

path = path + '-' + i

count += 1  # 记录层数

get_count(dict_test[i])

else:

try:

# 如果不是字典 则是键值对,查询value值是不是3,当前i包含两个内容,一个是key,一个是value

if dict_test[i] == 3:

# 找到了value =3 的值

result.append(f"路径是: %s,在第%d层" % (path + '-' + i, count))

except Exception as  result:  # 虽然字典限定了写法,为了增加健壮性 此位置使用try指令,避免类型错误

print(result)

continue

if __name__ == '__main__':

get_count(simple_dict)  # 执行递归函数

[print(str(i + 1) + ':' + j) for i, j in enumerate(result)]  # 打印结果

'''

结果:

1:路径是: Large_dict-middle_dict1-middle_dict2-small_dict3,在第3层

2:路径是: Large_dict-middle_dict1-middle_dict2-small_dict5-small_dict22,在第4层

'''

python字典操作函数

字典是一种通过名字或者关键字引用的得数据结构,其键可以是数字、字符串、元组,这种结构类型也称之为映射。字典类型是Python中唯一内建的映射类型,基本的操作包括如下:

(1)len():返回字典中键—值对的数量;

(2)d[k]:返回关键字对于的值;

(3)d[k]=v:将值关联到键值k上;

(4)del d[k]:删除键值为k的项;

(5)key in d:键值key是否在d中,是返回True,否则返回False。

(6)clear函数:清除字典中的所有项

(7)copy函数:返回一个具有相同键值的新字典;deepcopy()函数使用深复制,复制其包含所有的值,这个方法可以解决由于副本修改而使原始字典也变化的问题

(8)fromkeys函数:使用给定的键建立新的字典,键默认对应的值为None

(9)get函数:访问字典成员

(10)has_key函数:检查字典中是否含有给出的键

(11)items和iteritems函数:items将所有的字典项以列表方式返回,列表中项来自(键,值),iteritems与items作用相似,但是返回的是一个迭代器对象而不是列表

(12)keys和iterkeys:keys将字典中的键以列表形式返回,iterkeys返回键的迭代器

(13)pop函数:删除字典中对应的键

(14)popitem函数:移出字典中的项

(15)setdefault函数:类似于get方法,获取与给定键相关联的值,也可以在字典中不包含给定键的情况下设定相应的键值

(16)update函数:用一个字典更新另外一个字典

(17) values和itervalues函数:values以列表的形式返回字典中的值,itervalues返回值得迭代器,由于在字典中值不是唯一的,所以列表中可以包含重复的元素

一、字典的创建

1.1 直接创建字典

d={'one':1,'two':2,'three':3}

printd

printd['two']

printd['three']

运算结果:

=======RESTART: C:UsersMr_DengDesktoptest.py=======

{'three':3,'two':2,'one':1}

1.2 通过dict创建字典

# _*_ coding:utf-8 _*_

items=[('one',1),('two',2),('three',3),('four',4)]

printu'items中的内容:'

printitems

printu'利用dict创建字典,输出字典内容:'

d=dict(items)

printd

printu'查询字典中的内容:'

printd['one']

printd['three']

运算结果:

=======RESTART: C:UsersMr_DengDesktoptest.py=======

items中的内容:

[('one',1), ('two',2), ('three',3), ('four',4)]

利用dict创建字典,输出字典内容:

{'four':4,'three':3,'two':2,'one':1}

查询字典中的内容:

或者通过关键字创建字典

# _*_ coding:utf-8 _*_

d=dict(one=1,two=2,three=3)

printu'输出字典内容:'

printd

printu'查询字典中的内容:'

printd['one']

printd['three']

运算结果:

=======RESTART: C:UsersMr_DengDesktoptest.py=======

输出字典内容:

{'three':3,'two':2,'one':1}

查询字典中的内容:

二、字典的格式化字符串

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3,'four':4}

printd

print"three is %(three)s."%d

运算结果:

=======RESTART: C:UsersMr_DengDesktoptest.py=======

{'four':4,'three':3,'two':2,'one':1}

threeis3.

三、字典方法

3.1 clear函数:清除字典中的所有项

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3,'four':4}

printd

d.clear()

printd

运算结果:

=======RESTART: C:UsersMr_DengDesktoptest.py=======

{'four':4,'three':3,'two':2,'one':1}

{}

请看下面两个例子

3.1.1

# _*_ coding:utf-8 _*_

d={}

dd=d

d['one']=1

d['two']=2

printdd

d={}

printd

printdd

运算结果:

=======RESTART: C:UsersMr_DengDesktoptest.py=======

{'two':2,'one':1}

{}

{'two':2,'one':1}

3.1.2

# _*_ coding:utf-8 _*_

d={}

dd=d

d['one']=1

d['two']=2

printdd

d.clear()

printd

printdd

运算结果:

=======RESTART: C:UsersMr_DengDesktoptest.py=======

{'two':2,'one':1}

{}

{}

3.1.2与3.1.1唯一不同的是在对字典d的清空处理上,3.1.1将d关联到一个新的空字典上,这种方式对字典dd是没有影响的,所以在字典d被置空后,字典dd里面的值仍旧没有变化。但是在3.1.2中clear方法清空字典d中的内容,clear是一个原地操作的方法,使得d中的内容全部被置空,这样dd所指向的空间也被置空。

3.2 copy函数:返回一个具有相同键值的新字典

# _*_ coding:utf-8 _*_

x={'one':1,'two':2,'three':3,'test':['a','b','c']}

printu'初始X字典:'

printx

printu'X复制到Y:'

y=x.copy()

printu'Y字典:'

printy

y['three']=33

printu'修改Y中的值,观察输出:'

printy

printx

printu'删除Y中的值,观察输出'

y['test'].remove('c')

printy

printx

运算结果:

=======RESTART: C:UsersMr_DengDesktoptest.py=======

初始X字典:

{'test': ['a','b','c'],'three':3,'two':2,'one':1}

X复制到Y:

Y字典:

{'test': ['a','b','c'],'one':1,'three':3,'two':2}

修改Y中的值,观察输出:

{'test': ['a','b','c'],'one':1,'three':33,'two':2}

{'test': ['a','b','c'],'three':3,'two':2,'one':1}

删除Y中的值,观察输出

{'test': ['a','b'],'one':1,'three':33,'two':2}

{'test': ['a','b'],'three':3,'two':2,'one':1}

注:在复制的副本中对值进行替换后,对原来的字典不产生影响,但是如果修改了副本,原始的字典也会被修改。deepcopy函数使用深复制,复制其包含所有的值,这个方法可以解决由于副本修改而使原始字典也变化的问题。

# _*_ coding:utf-8 _*_

fromcopyimportdeepcopy

x={}

x['test']=['a','b','c','d']

y=x.copy()

z=deepcopy(x)

printu'输出:'

printy

printz

printu'修改后输出:'

x['test'].append('e')

printy

printz

运算输出:

=======RESTART: C:UsersMr_DengDesktoptest.py=======

输出:

{'test': ['a','b','c','d']}

{'test': ['a','b','c','d']}

修改后输出:

{'test': ['a','b','c','d','e']}

{'test': ['a','b','c','d']}

3.3 fromkeys函数:使用给定的键建立新的字典,键默认对应的值为None

# _*_ coding:utf-8 _*_

d=dict.fromkeys(['one','two','three'])

printd

运算输出:

=======RESTART: C:UsersMr_DengDesktoptest.py=======

{'three':None,'two':None,'one':None}

或者指定默认的对应值

# _*_ coding:utf-8 _*_

d=dict.fromkeys(['one','two','three'],'unknow')

printd

运算结果:

=======RESTART: C:UsersMr_DengDesktoptest.py=======

{'three':'unknow','two':'unknow','one':'unknow'}

3.4 get函数:访问字典成员

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3}

printd

printd.get('one')

printd.get('four')

运算结果:

=======RESTART: C:UsersMr_DengDesktoptest.py=======

{'three':3,'two':2,'one':1}

1

None

注:get函数可以访问字典中不存在的键,当该键不存在是返回None

3.5 has_key函数:检查字典中是否含有给出的键

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3}

printd

printd.has_key('one')

printd.has_key('four')

运算结果:

=======RESTART: C:UsersMr_DengDesktoptest.py=======

{'three':3,'two':2,'one':1}

True

False

3.6 items和iteritems函数:items将所有的字典项以列表方式返回,列表中项来自(键,值),iteritems与items作用相似,但是返回的是一个迭代器对象而不是列表

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3}

printd

list=d.items()

forkey,valueinlist:

  printkey,':',value

运算结果:

=======RESTART: C:UsersMr_DengDesktoptest.py=======

{'three':3,'two':2,'one':1}

three :3

two :2

one :1

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3}

printd

it=d.iteritems()

fork,vinit:

  print"d[%s]="%k,v

运算结果:

=======RESTART: C:UsersMr_DengDesktoptest.py=======

{'three':3,'two':2,'one':1}

d[three]=3

d[two]=2

d[one]=1

3.7 keys和iterkeys:keys将字典中的键以列表形式返回,iterkeys返回键的迭代器

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3}

printd

printu'keys方法:'

list=d.keys()

printlist

printu'niterkeys方法:'

it=d.iterkeys()

forxinit:

  printx

运算结果:

=======RESTART: C:UsersMr_DengDesktoptest.py=======

{'three':3,'two':2,'one':1}

keys方法:

['three','two','one']

iterkeys方法:

three

two

one

3.8 pop函数:删除字典中对应的键

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3}

printd

d.pop('one')

printd

运算结果:

=======RESTART: C:UsersMr_DengDesktoptest.py=======

{'three':3,'two':2,'one':1}

{'three':3,'two':2}

3.9 popitem函数:移出字典中的项

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3}

printd

d.popitem()

printd

运算结果:

=======RESTART: C:UsersMr_DengDesktoptest.py=======

{'three':3,'two':2,'one':1}

{'two':2,'one':1}

3.10 setdefault函数:类似于get方法,获取与给定键相关联的值,也可以在字典中不包含给定键的情况下设定相应的键值

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3}

printd

printd.setdefault('one',1)

printd.setdefault('four',4)

printd

运算结果:

{'three':3,'two':2,'one':1}

{'four':4,'three':3,'two':2,'one':1}

3.11 update函数:用一个字典更新另外一个字典

# _*_ coding:utf-8 _*_

d={

  'one':123,

  'two':2,

  'three':3

  }

printd

x={'one':1}

d.update(x)

printd

运算结果:

=======RESTART: C:UsersMr_DengDesktoptest.py=======

{'three':3,'two':2,'one':123}

{'three':3,'two':2,'one':1}

3.12 values和itervalues函数:values以列表的形式返回字典中的值,itervalues返回值得迭代器,由于在字典中值不是唯一的,所以列表中可以包含重复的元素

# _*_ coding:utf-8 _*_

d={

  'one':123,

  'two':2,

  'three':3,

  'test':2

  }

printd.values()

运算结果:

=======RESTART: C:UsersMr_DengDesktoptest.py=======

[2,3,2,123]

python中字典常用的方法有哪些,分别有什么作用?

写法:字典序列[key] = 值 ***字典为可变类型

常用方法:

1、# 新增字典中的数据

dict1 = {'name':'huu','age':20,'gender':'男'}

dict1['id'] = 133

print(dict1)

2、# 修改字典中的数据

dict1['name'] = 'xiauaiguai'

print(dict1)

3、删除字典或删除字典中指定键值对

del()/del:

dict1 = {'name':'huanghu','age':30,'gender':'男'}

# del(dict1) 直接将字典删除了,运行报错

del dict1['name']

print(dict1)

# del dict1[names] 删除不存在的key,运行报错

4、清空字典

clear():

dict1.clear() # 清空字典

print(dict1)

5、查找

key值查找

如果当前查找的key存在则返回对应的值,否则则报错

函数查找

get():如果当前查找的key不存在则返回第二个参数值(默认值),

如果省略第二个参数则返回 None

key()

dict1 = {'name':'huhu','age':20,'gender':'男'}

print(dict1['name']) # huhu

print(dict1['id']) # 报错

# 1, get()查找

print(dict1.get('name')) # huanghu

print(dict1.get('id',133)) # 133--如果当前查找的key不存在则返回第二个参数值(默认值)

print(dict1.get('id')) # None--如果省略第二个参数则返回 None

# 2, keys() 查找字典中所有的key,返回可迭代对象

print(dict1.keys()) # dict_keys(['name', 'age', 'gender'])

# 3,values() 查找字典中所有的values,

print(dict1.values()) # dict_values(['huanghu', 30, '男'])

# 4, items() 查找字典中所有的键值对,返回可迭代对象,里面的数据是元组,

元组数据1是字典中的key,元组数据2是字典key对应的值

print(dict1.items()) # dict_items([('name', 'huahu'), ('age', 20), ('gender', '男')])

利用Python进行数据分析笔记:3.1数据结构

元组是一种固定长度、不可变的Python对象序列。创建元组最简单的办法是用逗号分隔序列值:

tuple 函数将任意序列或迭代器转换为元组:

中括号 [] 可以获取元组的元素, Python中序列索引从0开始 :

元组一旦创建,各个位置上的对象是无法被修改的,如果元组的一个对象是可变的,例如列表,你可以在它内部进行修改:

可以使用 + 号连接元组来生成更长的元组:

元组乘以整数,则会和列表一样,生成含有多份拷贝的元组:

将元组型的表达式赋值给变量,Python会对等号右边的值进行拆包:

拆包的一个常用场景就是遍历元组或列表组成的序列:

*rest 用于在函数调用时获取任意长度的位置参数列表:

count 用于计量某个数值在元组中出现的次数:

列表的长度可变,内容可以修改。可以使用 [] 或者 list 类型函数来定义列表:

append 方法将元素添加到列表尾部:

insert 方法可以将元素插入到指定列表位置:

( 插入位置范围在0到列表长度之间 )

pop 是 insert 的反操作,将特定位置的元素移除并返回:

remove 方法会定位第一个符合要求的值并移除它:

in 关键字可以检查一个值是否在列表中;

not in 表示不在:

+ 号可以连接两个列表:

extend 方法可以向该列表添加多个元素:

使用 extend 将元素添加到已经存在的列表是更好的方式,比 + 快。

sort 方法可以对列表进行排序:

key 可以传递一个用于生成排序值的函数,例如通过字符串的长度进行排序:

bisect.bisect 找到元素应当被插入的位置,返回位置信息

bisect.insort 将元素插入到已排序列表的相应位置保持序列排序

bisect 模块的函数并不会检查列表是否已经排序,因此对未排序列表使用bisect不会报错,但是可能导致不正确结果

切片符号可以对大多数序列类型选取子集,基本形式是 [start:stop]

起始位置start索引包含,结束位置stop索引不包含

切片还可以将序列赋值给变量:

start和stop可以省略,默认传入起始位置或结束位置,负索引可以从序列尾部进行索引:

步进值 step 可以在第二个冒号后面使用, 意思是每隔多少个数取一个值:

对列表或元组进行翻转时,一种很聪明的用法时向步进值传值-1:

dict(字典)可能是Python内建数据结构中最重要的,它更为常用的名字是 哈希表 或者 关联数组 。

字典是键值对集合,其中键和值都是Python对象。

{} 是创建字典的一种方式,字典中用逗号将键值对分隔:

你可以访问、插入或设置字典中的元素,:

in 检查字典是否含有一个键:

del 或 pop 方法删除值, pop 方法会在删除的同时返回被删的值,并删除键:

update 方法将两个字典合并:

update方法改变了字典元素位置,对于字典中已经存在的键,如果传给update方法的数据也含有相同的键,则它的值将会被覆盖。

字典的值可以是任何Python对象,但键必须是不可变的对象,比如标量类型(整数、浮点数、字符串)或元组(且元组内对象也必须是不可变对象)。

通过 hash 函数可以检查一个对象是否可以哈希化(即是否可以用作字典的键):

集合是一种无序且元素唯一的容器。

set 函数或者是用字面值集与大括号,创建集合:

union 方法或 | 二元操作符获得两个集合的联合即两个集合中不同元素的并集:

intersection 方法或 操作符获得交集即两个集合中同时包含的元素:

常用的集合方法列表:

和字典类似,集合的元素必须是不可变的。如果想要包含列表型的元素,必须先转换为元组:

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。