python基础系列——字典知识点,函数及操作(持续更新中)

前言:

此文为本人在学习python过程中,整理出来的学习笔记。主要参考书目有:
1、《python编程:从入门到实践》;
2、《python学习手册》;
3、《像计算机科学家一样思考Python》

一 字典简介

字典可以当做是无序的集合,字典与列表最主要的差别在于:字典中的元素(也可叫值,value)是通过键(key)来存取的,而不是通过偏移存取。
字典的主要属性如下:

  1. 通过键而不是偏移量来读取
  2. 任意对象的无序集合
  3. 可变长、异构、任意嵌套
  4. 属于可变映射类型
  5. 对象引用表

字典常用操作表

在这里插入图片描述

二 字典的基本操作

2.1 字典的创建

字典可通过花括号{},中间加上’key’ : ‘value’,的方式直接创建,如:

#为了代码的美观可用此种方式书写。
info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}
print(info)
#运行结果:{'name': 'Tom', 'age': 18, 'job': ['designer', 'cook']}

字典的键可以是:数字、字符串,但不可是列表等容器
字典的值可以是任意对象,如:数字,字符串,列表,字典等

2.1.1 遍历的方式创建字典

也可以通过对两个相同长度的列表进行遍历,并分别赋值给键和值,来创建一个字典,如:

ageinfo = {}
names = ['小明','小李','小周','小二']
foods = ['18','20','26','24']

for num in range(0,len(names)):
	ageinfo[names[num]] = foods[num]

print(ageinfo)
#运行结果:{'小明': '18', '小李': '20', '小周': '26', '小二': '24'}

上述代码可用一个更简单的方式来创建
利用zip函数:

names = ['小明','小李','小周','小二']
ages = ['18','20','26','24']

ageinfo = dict(zip(names,ages))  #zip函数从两个列表中分别取一项!
print(ageinfo)
#运行结果:{'小明': '18', '小李': '20', '小周': '26', '小二': '24'}

2.1.2 其他几种字典的创建方法

ageinfo = dict([('name','小明'),('age',26)])
print(ageinfo)
#运行结果:{'name': '小明', 'age': 26}

另外一种方法:


ageinfo = dict(name = '小明',age = 26)
print(ageinfo)
#运行结果:{'name': '小明', 'age': 26}

2.2 字典值的修改

字典和列表一样,也属于可变序列,可直接修改:

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

info['age'] = 22
print(info)
#运行结果:{'name': 'Tom', 'age': 22, 'job': ['designer', 'cook']}

2.3 len等内置函数

len函数也可作用于字典,获取的是字典中键的个数。

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

print(len(info))
#运行结果:3

in 方法:in方法默认查找被查找元素是否在字典键中(keys()方法为提取字典中的键),返回一个布尔值。

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

print('name' in info)
#运行结果:True
print('age' in info.keys())
#运行结果:True

in也可用来寻找字典值中的元素:

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

print(18 in info.values())
#运行结果:True

#但是注意!!!
print('cook' in info.values())
#运行结果:False 

三 字典方法调用

3.1 keys,values方法

keys和values方法可直接获得一个类似列表的对象:

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

print(info.keys())
#运行结果:dict_keys(['name', 'age', 'job'])
print(info.values())
#运行结果:dict_values(['Tom', 18, ['designer', 'cook']])

也可用list函数来创建一个真实的列表:

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

keys_list = list(info.keys())
print(keys_list)
#运行结果:['name', 'age', 'job']

3.2 items方法

items方法可同时输出字典的键和值:

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

print(info.items())
#运行结果:dict_items([('name', 'Tom'), ('age', 18), ('job', ['designer', 'cook'])])

3.2.1 字典的遍历

字典键的遍历:

#接上字典代码
for key in info.keys():
	print(key)
'''
运行结果:
name
age
job '''

字典值得遍历:

for value in info.values():
	print(value)
'''运行结果为:
Tom
18
['designer', 'cook']
'''

字典值与键的遍历:

for key , value in info.items():
	print(key,value)
'''
运行结果:
name Tom
age 18
job ['designer', 'cook']
'''

3.3 pop与del方法

与列表类似,字典也可通过pop,del方法来删除其内部元素:

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

info.pop('name')
print(info)
#运行结果:{'age': 18, 'job': ['designer', 'cook']}

del 用法

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

del info['age']
print(info)
#运行结果:{'name': 'Tom', 'job': ['designer', 'cook']}

3.4 update方法

字典的update方法有点类似于合并:

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

info_2 = {'add' : '北京'}

info.update(info_2)
print(info)
#运行结果:{'name': 'Tom', 'age': 18, 'job': ['designer', 'cook'], 'add': '北京'}

update会覆盖两个字典中重复的键的值:

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

info_2 = {
	'add' : '北京',
	'age' : 25
}

info.update(info_2)
print(info)
#运行结果:{'name': 'Tom', 'age': 25, 'job': ['designer', 'cook'], 'add': '北京'}

3.5 get方法

get方法用的比较少,可以获得键对应的值。但其特殊地方在于,当需获取的键在字典中不存在时,返回None,而不会报错。如:

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

print(info.get('name'))
#运行结果:Tom
print(info.get('add'))
#运行结果:None
print(info.get('add','beijing'))
#运行结果:beijing

3.6 fromkeys方法

formkeys也是一种创建字典的方法,用这个方法可创建一个具有相同值得初始化的一个列表:

ageinfo = dict.fromkeys(['小明','小李','小周','小二'],0)
print(ageinfo)
运行结果:{'小明': 0, '小李': 0, '小周': 0, '小二': 0}

其也可对一个已存在的字典进行初始化操作:

info = {
	'name' : 'Tom',
	'age' : 18,
	'job' : ['designer','cook']
}

initinfo = info.fromkeys(info.keys(),0)
print(initinfo)
#运行结果:{'name': 0, 'age': 0, 'job': 0}

也可以用字符串来快速创建一个具有初始化值得字典:

infodict = dict.fromkeys('abcdefg') #不传入值参数,则默认为None
print(infodict)
#运行结果:{'a': None, 'b': None, 'c': None, 'd': None, 'e': None, 'f': None, 'g': None}

3.7 字典解析

字典解析与列表解析一样,后期将会安排专门章节进行介绍。

d = {number : number**2 for number in [1,2,3,4]}
print(d)
#运行结果:{1: 1, 2: 4, 3: 9, 4: 16}

3.8 有序的打印字典的值

因字典是无序的组合,所以在需要按特定顺序的输出字典中的值有一定麻烦,可采用以下方法:

info = {'2':'b','1':'a','5':'e','3':'c','4':'d'}
#直接遍历得到的为无序的值:
for key in info:
	print(info[key],end = '-')
#运行结果为:b-a-e-c-d-

for key in sorted(info):
	print(info[key,end = '-'])
#运行结果:a-b-c-d-e-

结束语:

以上为本人根据所阅读书籍、博客、视频学习后,所整理出的内容。
因学习时间有限,有不足及错误地方,欢迎大家指出。
整理不易,欢迎点赞,收藏,转载(请注明出处,如需转到其他平台请私信!)

猜你喜欢

转载自blog.csdn.net/zhouz92/article/details/102497409