Python 十个字典用法使用技巧归纳

作者:Python学习与数据挖掘 时间:2023-10-14 16:52:54 

大家好,本期给大家带来Python字典11个方法的全面解析,希望对你有所帮助。

字典(Dictionary)是Python提供的一种常用的数据结构,它用于存放具有映射关系的数据,由键(key)和值(value)成对组成,键和值中间以冒号:隔开,项之间用逗号隔开,整个字典由大括号{}括起来,格式如下:


dic = {key1 : value1, key2 : value2 }

字典也被称作关联数组或哈希表,下面是几种常见的字典创建方式:


# 方法1
dic1 = { 'Author' : 'Python' , 'age' : 99 , 'sex' : '男' }

# 方法2
lst = [('Author', 'Python'), ('age', 99), ('sex', '男')]
dic2 = dict(lst)

# 方法3
dic3 = dict( Author = 'Python', age = 99, sex = '男')

# 方法4
list1 = ['Author', 'age', 'sex']
list2 = ['Python', 99, '男']
dic4 = dict(zip(list1, list2))

字典创建的方式还有很多种,这里不再赘述。

字典由 dict 类代表,可以使用 dir(dict) 来查看该类包含哪些方法,输入命令,可以看到如下输出结果:


print('methods = ',methods)

methods = ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

字典的方法和属性有很多种,这里我们重点介绍以下11种方法:


['clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

1.dict.clear()

clear() 用于清空字典中所有元素(键-值对),对一个字典执行 clear() 方法之后,该字典就会变成一个空字典:


list1 = ['Author', 'age', 'sex']
list2 = ['Python', 99, '男']
dic1 = dict(zip(list1, list2))
# dic1 = {'Author': 'Python', 'age': 99, 'sex': '男'}

dic1.clear()
# dic1 = {}

2.dict.copy()

copy() 用于返回一个字典的浅拷贝:


list1 = ['Author', 'age', 'sex']
list2 = ['Python', 99, '男']
dic1 = dict(zip(list1, list2))

dic2 = dic1 # 浅拷贝: 引用对象
dic3 = dic1.copy() # 浅拷贝:深拷贝父对象(一级目录),子对象(二级目录)不拷贝,还是引用
dic1['age'] = 18

# dic1 = {'Author': 'Python', 'age': 18, 'sex': '男'}
# dic2 = {'Author': 'Python', 'age': 18, 'sex': '男'}
# dic3 = {'Author': 'Python', 'age': 99, 'sex': '男'}

其中 dic2 是 dic1 的引用,所以输出结果是一致的,dic3 父对象进行了深拷贝,不会随dic1 修改而修改,子对象是浅拷贝所以随 dic1 的修改而修改,注意父子关系。

拓展深拷贝:copy.deepcopy()


import copy

list1 = ['Author', 'age', 'sex']
list2 = ['Python', [18,99], '男']
dic1 = dict(zip(list1, list2))

dic2 = dic1
dic3 = dic1.copy()
dic4 = copy.deepcopy(dic1)
dic1['age'].remove(18)
dic1['age'] = 20

# dic1 = {'Author': 'Python', 'age': 20, 'sex': '男'}
# dic2 = {'Author': 'Python', 'age': 20, 'sex': '男'}
# dic3 = {'Author': 'Python', 'age': [99], 'sex': '男'}
# dic4 = {'Author': 'Python', 'age': [18, 99], 'sex': '男'}

dic2 是 dic1 的引用,所以输出结果是一致的;dic3 父对象进行了深拷贝,不会随dic1 修改而修改,子对象是浅拷贝所以随 dic1 的修改而修改;dic4 进行了深拷贝,递归拷贝所有数据,相当于完全在另外内存中新建原字典,所以修改dic1不会影响dic4的数据

3.dict.fromkeys()

fromkeys() 使用给定的多个键创建一个新字典,值默认都是 None,也可以传入一个参数作为默认的值:


list1 = ['Author', 'age', 'sex']
dic1 = dict.fromkeys(list1)
dic2 = dict.fromkeys(list1, 'Python')

# dic1 = {'Author': None, 'age': None, 'sex': None}
# dic2 = {'Author': 'Python', 'age': 'Python', 'sex': 'Python'}

4.dict.get()

get() 用于返回指定键的值,也就是根据键来获取值,在键不存在的情况下,返回 None,也可以指定返回值:


list1 = ['Author', 'age', 'sex']
list2 = ['Python', [18,99], '男']
dic1 = dict(zip(list1, list2))

Author = dic1.get('Author')
# Author = Python
phone = dic1.get('phone')
# phone = None
phone = dic1.get('phone','12345678')
# phone = 12345678

5.dict.items()

items() 获取字典中的所有键-值对,一般情况下可以将结果转化为列表再进行后续处理:


list1 = ['Author', 'age', 'sex']
list2 = ['Python', [18,99], '男']
dic1 = dict(zip(list1, list2))
items = dic1.items()
print('items = ', items)
print(type(items))
print('items = ', list(items))

# items = dict_items([('Author', 'Python'), ('age', [18, 99]), ('sex', '男')])
# <class 'dict_items'>
# items = [('Author', 'Python'), ('age', [18, 99]), ('sex', '男')]

6.dict.keys()

keys() 返回一个字典所有的键:


list1 = ['Author', 'age', 'sex']
list2 = ['Python', [18,99], '男']
dic1 = dict(zip(list1, list2))
keys = dic1.keys()
print('keys = ', keys)
print(type(keys))
print('keys = ', list(keys))

# keys = dict_keys(['Author', 'age', 'sex'])
# <class 'dict_keys'>
# keys = ['Author', 'age', 'sex']

7.dict.pop()

pop() 返回指定键对应的值,并在原字典中删除这个键-值对:


list1 = ['Author', 'age', 'sex']
list2 = ['Python', [18,99], '男']
dic1 = dict(zip(list1, list2))
sex = dic1.pop('sex')
print('sex = ', sex)
print('dic1 = ',dic1)

# sex = 男
# dic1 = {'Author': 'Python', 'age': [18, 99]}

8.dict.popitem()

popitem() 删除字典中的最后一对键和值:


list1 = ['Author', 'age', 'sex']
list2 = ['Python', [18,99], '男']
dic1 = dict(zip(list1, list2))
dic1.popitem()
print('dic1 = ',dic1)

# dic1 = {'Author': 'Python', 'age': [18, 99]}

9.dict.setdefault()

setdefault() 和 get() 类似, 但如果键不存在于字典中,将会添加键并将值设为default:


list1 = ['Author', 'age', 'sex']
list2 = ['Python', [18,99], '男']
dic1 = dict(zip(list1, list2))
dic1.setdefault('Author', '')
print('dic1 = ',dic1)
# dic1 = {'Author': 'Python', 'age': [18, 99], 'sex': '男'}
dic1.setdefault('name', '')
print('dic1 = ',dic1)
# dic1 = {'Author': 'Python', 'age': [18, 99], 'sex': '男', 'name': ''}

10.dict.update(dict1)

update() 字典更新,将字典dict1的键-值对更新到dict里,如果被更新的字典中己包含对应的键-值对,那么原键-值对会被覆盖,如果被更新的字典中不包含对应的键-值对,则添加该键-值对:


list1 = ['Author', 'age', 'sex']
list2 = ['Python', [18,99], '男']
dic1 = dict(zip(list1, list2))
print('dic1 = ',dic1)
# dic1 = {'Author': 'Python', 'age': [18, 99], 'sex': '男'}

list3 = ['Author', 'phone' ]
list4 = ['', 12345678]
dic2 = dict(zip(list3, list4))
print('dic2 = ',dic2)
# dic2 = {'Author': '', 'phone': 12345678}

dic1.update(dic2)
print('dic1 = ',dic1)
# dic1 = {'Author': '', 'age': [18, 99], 'sex': '男', 'phone': 12345678}

11.dict.values()

values() 返回一个字典所有的值:


list1 = ['Author', 'age', 'sex']
list2 = ['Python', [18,99], '男']
dic1 = dict(zip(list1, list2))
values = dic1.values()
print('values = ', values)
print(type(values))
print('values = ', list(values))

# values = dict_values(['Python', [18, 99], '男'])
# <class 'dict_values'>
# values = ['Python', [18, 99], '男']

来源:https://blog.csdn.net/weixin_38037405/article/details/122726343

标签:Python,字典,创建
0
投稿

猜你喜欢

  • Python lxml模块的基本使用方法分析

    2023-01-31 04:59:40
  • sqlserver 存储过程带事务 拼接id 返回值

    2012-11-30 20:06:39
  • 怎么才能限制SQL Server只能让指定的机器连接

    2024-01-15 04:50:50
  • python3实现字符串操作的实例代码

    2023-08-23 06:24:31
  • yolov5特征图可视化的使用步骤

    2022-07-22 01:25:40
  • python解析模块(ConfigParser)使用方法

    2022-06-15 11:39:06
  • python 利用opencv实现图像网络传输

    2023-05-27 12:52:16
  • Python实现mysql数据库中的SQL文件生成和导入

    2024-01-22 01:04:41
  • Python使用sklearn库实现的各种分类算法简单应用小结

    2022-08-05 22:37:59
  • 详解MySQL中ALTER命令的使用

    2024-01-26 12:27:25
  • python 实现对文件夹中的图像连续重命名方法

    2022-11-04 02:04:08
  • python文件操作的基础详细讲解(write、read、readlines、readline)

    2021-04-05 19:31:44
  • nodejs express路由匹配控制及Router模块化使用详解

    2024-05-11 10:17:18
  • 教你快速上手Selenium爬虫,万物皆可爬

    2022-01-02 18:44:31
  • tensorflow 保存模型和取出中间权重例子

    2021-05-11 07:30:11
  • Python双端队列deque的实现

    2022-07-07 02:37:29
  • XML:OpenSearch 浏览器指定搜索应用

    2010-05-04 19:37:00
  • SQL Server 2008图文安装教程第1/2页

    2024-01-12 18:54:21
  • Python趣味挑战之用pygame实现飞机塔防游戏

    2022-07-18 04:00:02
  • python机器学习Logistic回归原理推导

    2022-12-17 00:45:15
  • asp之家 网络编程 m.aspxhome.com