Python语言基础
Python语言进阶
Python数据结构

Python 字典

搞懂Python字典的基本操作
字典是无序可变的序列,元素以“键值对(key-value)”的形式存储。 字典相对于列表(list)和元组(tuple)是有序的序列。 字典中的元素是通过键来存取的,列表是通过下标索引存取的。 字典用 { } 标识,是一个键(key) : 值(value) 的集合,key值必须保障唯一。 字典格式为{'key':'value1', 'key2':'value2', ..., 'keyn':valuen} 字典键必须是唯一的,但值不需要,值可以取任何数据类型。

创建字典

dict = {}
dict['name'] = "lidihuo"
dict[1] = "Hello World"
dict1 = {'name': 'lidihuo','course':'python', 'site': 'www.lidihuo.com'}
dict2 = {(1,2,3): 'great', 30: [1,2,3]} # 使用元组和列表作为key和value
print(dict['name']) # 输出键为 'name' 的值
print(dict[1]) # 输出键为1的值
print(dict1) # 输出完整的字典
print(dict1.keys()) # 输出所有键
print(dict1.values()) # 输出所有值
print(dict2) # 输出完整的字典
执行结果:
lidihuo
Hello World
{'name': 'lidihuo', 'course': 'python', 'site': 'www.lidihuo.com'}
dict_keys(['name', 'course', 'site'])
dict_values(['lidihuo', 'python', 'www.lidihuo.com'])
{(1, 2, 3): 'great', 30: [1, 2, 3]}

访问字典

dict是通过键来访问对应的值。因为字典中的元素是无序的,每个元素的位置都不固定,所以字典也不能像列表和元组那样,采用下标来访问元素。
dict元素的具体格式为:dictname[key]。dictname 表示dict变量的名字,key 表示键名。
dict = {'name': 'lidihuo','course':'python', 'site': 'www.lidihuo.com'}
print(dic['name']) # 输出键对应的值
执行结果:
lidihuo
Python 中更推荐使用get() 方法来获取指定键对应的值。语法格式为:dictname.get(key[,default]),其中,dictname 表示字典变量的名字;key 表示指定的键; default 用于指定要查询的键不存在时,此方法返回的默认值,如果不手动指定,会返回 None。
dict = {'name': 'lidihuo','course':'python', 'site': 'www.lidihuo.com'}
print(dict.get('name'))
执行结果:
lidihuo

修改字典

字典修改可以用新内容的覆盖,修改或删除已有键/值对操作如下:
dict = {'name': 'lidihuo','course':'python', 'site': 'www.lidihuo.com'}
dict['name'] = 'hello' # 更新 name值
dict['place'] = 'china' # 添加值
print(dict) # 输出键对应的值
执行结果:
lidihuo

删除字典

字典可以进行单一元素删除,也能清空所有数据,具体操作如下:
dict = {'name': 'lidihuo','course':'python', 'site': 'www.lidihuo.com'}
del dict['name'] # 删除单一键
print(dict) # 输出键对应的值
dict.clear() # 删除单一键
print(dict) # 输出键对应的值
执行结果:
{'course': 'python', 'site': 'www.lidihuo.com'}
{}

字典健判断

字典中键值判断,可以使用 in 或 not in 运算符。需要指出的是,对于 dict 而言,in 或 not in 运算符都是基于 key 来判断的。具体操作如下:
dict = {'name': 'lidihuo','course':'python', 'site': 'www.lidihuo.com'}
print('name' in dict) # 结果应为True
print('hello' in dict) # 结果应为False
执行结果:
True
False

字典常用方法

字典中常用的方法有keys()、values()、items()、copy()、update()、pop()、popitem(),具体用法如下:
dict = {'name': 'lidihuo','course':'python', 'site': 'www.lidihuo.com'}
print(dict.keys()) # 返回字典中的所有键(key)
print(dict.values()) # 返回字典中所有键对应的值(value)
print(dict.items()) # 返回字典中所有的键值对(key-value)
print(dict.copy()) # 拷贝一个具有相同键值对的新字典
dict.update({'name': 'Jack','hello':'world'}) # 如果己存在对应的键值对,则覆盖,否则新添加
print(dict)
dict.pop('name') # 删除指定的键值对
print(dict)
dict.popitem() # 随机删除一个键值对
print(dict)
执行结果:
dict_keys(['name', 'course', 'site'])
dict_values(['lidihuo', 'python', 'www.lidihuo.com'])
dict_items([('name', 'lidihuo'), ('course', 'python'), ('site', 'www.lidihuo.com')])
{'name': 'lidihuo', 'course': 'python', 'site': 'www.lidihuo.com'}
{'name': 'Jack', 'course': 'python', 'site': 'www.lidihuo.com', 'hello': 'world'}
{'course': 'python', 'site': 'www.lidihuo.com', 'hello': 'world'}
{'course': 'python', 'site': 'www.lidihuo.com'}

使用字典格式化字符串

由于字典是键值对结构,这种结构可以巧妙的应用到字符串的格式化中,具体操作如下:
temp = '我是%(name)s平台, 本章讲解的是%(course)s课程, 具体内容可访问%(site)s网站查看'
dict = {'name': 'lidihuo','course':'python', 'site': 'www.lidihuo.com'}
print(temp % dict)
执行结果:
我是lidihuo平台, 本章讲解的是python课程, 具体内容可访问www.lidihuo.com网站查看

字典内置函数

序号 函数及描述 实例
1 len(dict)
计算字典元素个数,即键的总数。
>>> dict = {'name': 'lidihuo','course':'python', 'site': 'www.lidihuo.com'}
>>> len(dict)
3
2 str(dict)
输出字典,以可打印的字符串表示。
>>> dict = {'name': 'lidihuo','course':'python', 'site': 'www.lidihuo.com'}
>>> str(dict)
"{'name': 'lidihuo','course':'python', 'site': 'www.lidihuo.com'}"
3 type(variable)
返回输入的变量类型,如果变量是字典就返回字典类型。
>>> dict = {'name': 'lidihuo','course':'python', 'site': 'www.lidihuo.com'}
>>> type(dict)
<class 'dict'>

字典内置方法

序号 函数及描述
1 radiansdict.clear()
删除字典内所有元素
2 radiansdict.copy()
返回一个字典的浅复制
3 radiansdict.fromkeys()
创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
4 radiansdict.get(key, default=None)
返回指定键的值,如果键不在字典中返回 default 设置的默认值
5 key in dict
如果键在字典dict里返回true,否则返回false
6 radiansdict.items()
以列表返回可遍历的(键, 值) 元组数组
7 radiansdict.keys()
返回一个迭代器,可以使用 list() 来转换为列表
8 radiansdict.setdefault(key, default=None)
和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
9 radiansdict.update(dict2)
把字典dict2的键/值对更新到dict里
10 radiansdict.values()
返回一个迭代器,可以使用 list() 来转换为列表
11 pop(key[,default])
删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。
12 popitem()
随机返回并删除字典中的最后一对键和值。
昵称: 邮箱:
everyone 2020-09-21

Python字典操作方法:


clear() —— 从字典中删除所有项目。

copy()  —— 返回字典的浅表副本。

fromkeys(seq[, v])  —— 返回一个新字典,其中的键来自 序列 和值等于 v(默认为None)。

get(key[,d])  —— 返回的值 键。如果键 不存在,返回 d(默认为None)。

items() 以(键,值) —— 格式返回字典项的新对象。

keys()  —— 返回字典键的新对象。

pop(key[,d])  —— 用 键 并返回其值或 d 如果 键找不到。如果d 没有提供,并且 键找不到,它引发KeyError。

popitem()  —— 删除并返回一个任意项(key,value)。KeyError如果字典为空则引发。

setdefault(key[,d])  ——  如果 键在字典中。如果不是,则插入键 的值为 d 并返回 d(默认为None)。

update([other])  ——  使用以下项中的键/值对更新字典 其他,覆盖现有密钥。

values()  —— 返回字典值的新对象

Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4