当前位置: 首页 > news >正文

Python-字典,从基础到进阶用法大总结,进来查漏补缺

在这里插入图片描述
B站|公众号:啥都会一点的研究生

hello,我是啥都生,本期将Python中字典涉及的从基础到进阶用法,全部总结归纳,一起看看吧

计算机中的标准数据结构通常称为“映射”。在Python中,这种结构称为“字典”。当有键/值对数据(一个映射到输出的输入)时,使用字典是最方便的

假设有如下数据

name = "CaiXK"
age = 38
height = 163.1415926
hobby = ["rap", "basketball", "python"]
location = (34.228, 26.093)

name = "CaiXK"为例,构成完整键值对name"CaiXK"。有两种构建列表的方式将上述数据进行存储,第一种,直接使用大括号,键与值间用冒号配对,键值对间用逗号隔开

dict1 = {"name" : "CaiXK", "age" : 38, "height" : 163.1415926, "hobby" : ["rap", "basketball", "python"], "location" : (34.228, 26.093)}

print(dict1)

>>> {'name': 'CaiXK', 'age': 38, 'height': 163.1415926, 'hobby': ['rap', 'basketball', 'python'], 'location': (34.228, 26.093)}

第二种,使用内置方法dict(),注意与第一种方法的区别,键值用等号连接,键值对依然用逗号隔开

dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))

print(dict1)

>>> {'name': 'CaiXK', 'age': 38, 'height': 163.1415926, 'hobby': ['rap', 'basketball', 'python'], 'location': (34.228, 26.093)}

此外,使用fromkeys() 函数用于创建新字典,以序列中的元素做字典的键,所有键对应的初始值默认为None,可自定义初始值

keys = ('name', 'age', 'sex')

dict1 = dict.fromkeys(keys)
dict2 = dict.fromkeys(keys, 1)

print(dict1)
print(dict2)

>>> {'name': None, 'age': None, 'sex': None}
>>> {'name': 1, 'age': 1, 'sex': 1}

需特别注意的是,键不允许重复,若使用dict方式创建字典并多次给同一个键赋值,则会触发报错

dict1 = dict(name = "ZhangS", name = "LiS", name = "CaiXK")

print(dict1["name"])

>>> File "script.py", line 5
    dict1 = dict(name = "ZhangS", name = "LiS", name = "CaiXK")
                                  ^
SyntaxError: keyword argument repeated

Exited with error status 1

而使用大括号方式创建,则只保留最后一次写入的键值对数据

dict1 = {"name" : "ZhangS", "name" : "LiS", "name" : "CaiXK"}

print(dict1["name"])

>>> CaiXK

此外,必须保证键是不可变,也就是仅支持数字、字符串、元组

dict1 = {1 : 2, (22, 33) : "44", "55" : 66}

print(dict1)

>>> {1: 2, (22, 33): '44', '55': 66}

字典创建完成后,可以看做N个输入对应N个输出,输入为键,输出为值,且不限定输出类型。字典的取值通过键完成索引,如下所示,注意使用中括号且引号别落下

dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))

name = dict1["name"]

hobby_1 = dict1["hobby"][0]

print(name, " is good at ", hobby_1)

>>> CaiXK  is good at  rap

如果试图访问取出不存在的键,则会抛出如下错误

dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))

Girlfriend = dict1["girlfriend"]

print(Girlfriend)

>>> Traceback (most recent call last):
  File "script.py", line 3, in <module>
    Girlfriend = dict1["girlfriend"]
KeyError: 'girlfriend'

Exited with error status 1

而使用get获取键值,若键不存在,默认返回None,也支持自定义返回数据避免错误

dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))

Girlfriend = dict1.get("girlfriend")

print(Girlfriend)

Girlfriend = dict1.get("girlfriend", "Peter")

print(Girlfriend)

>>> None
>>> Peter

get()类似,若键不存在于字典中,使用setdefault自定义值,默认为None,但不同的是,会将该键值对添加至字典中

dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))

Girlfriend = dict1.setdefault("girlfriend", "Peter")

print(Girlfriend)
print(dict1)

>>> Peter
>>> {'name': 'CaiXK', 'age': 38, 'height': 163.1415926, 'hobby': ['rap', 'basketball', 'python'], 'location': (34.228, 26.093), 'girlfriend': 'Peter'}

因为字典是可变对象,支持修改,可以通过如下方式完成键值对的添加

dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))

dict1["girlfriend"] = "ZhangH" # Han

print(dict1)

>>> {'name': 'CaiXK', 'age': 38, 'height': 163.1415926, 'hobby': ['rap', 'basketball', 'python'], 'location': (34.228, 26.093), 'girlfriend': 'ZhangH'}

通过索引键并重新赋值完成修改

dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))

dict1["girlfriend"] = "LiYF" # ?

print(dict1)

>>> {'name': 'CaiXK', 'age': 38, 'height': 163.1415926, 'hobby': ['rap', 'basketball', 'python'], 'location': (34.228, 26.093), 'girlfriend': 'LiYF'}

使用del删除指定键值对

dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))

del dict1["location"]

print(dict1)

>>> {'name': 'CaiXK', 'age': 38, 'height': 163.1415926, 'hobby': ['rap', 'basketball', 'python']}

也可以删除整个字典

dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))

del dict1

print(dict1)

>>> Traceback (most recent call last):
  File "script.py", line 11, in <module>
    print(dict1)
NameError: name 'dict1' is not defined

Exited with error status 1

使用pop删除指定键值对并返回值

dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))

location = dict1.pop("location")

print(location, dict1)

>>> (34.228, 26.093) {'name': 'CaiXK', 'age': 38, 'height': 163.1415926, 'hobby': ['rap', 'basketball', 'python']}

使用popitem随机返回并删除字典中的最后一对键和值

dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))

data = dict1.popitem()

print(data, dict1)

>>> ('location', (34.228, 26.093)) {'name': 'CaiXK', 'age': 38, 'height': 163.1415926, 'hobby': ['rap', 'basketball', 'python']}

使用clear清空字典中的全部内容,注意与del不同,该对象仍存在

dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))

dict1.clear()

print(dict1)

>>> {}

使用copy完成字典的浅拷贝,避免因其可变带来的原始数据改动

dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))

dict2 = dict1
dict3 = dict1.copy()

dict1.popitem()

print(dict2)
print(dict3)

>>> {'name': 'CaiXK', 'age': 38, 'height': 163.1415926, 'hobby': ['rap', 'basketball', 'python']}
>>> {'name': 'CaiXK', 'age': 38, 'height': 163.1415926, 'hobby': ['rap', 'basketball', 'python'], 'location': (34.228, 26.093)}

判断键是否存在于字典中使用in

dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))

if name in dict1:
    print(True)

>>> True

使用update将另一个字典中的键值对更新到本字典中,若键重复,则以另一字典为默认

dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))
dict2 = dict(name = "WuYF", sex = "Female")

dict1.update(dict2)

print(dict1)

>>> {'name': 'WuYF', 'age': 38, 'height': 163.1415926, 'hobby': ['rap', 'basketball', 'python'], 'location': (34.228, 26.093), 'sex': 'Female'}

然后说说列表的遍历,第一种,使用items遍历每一个键值对

dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))

for item in dict1.items():
    print(item)

>>> ('name', 'CaiXK')
('age', 38)
('height', 163.1415926)
('hobby', ['rap', 'basketball', 'python'])
('location', (34.228, 26.093))

第二种,使用keys遍历字典中每个键,或者默认不使用内置方法

dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))

for key in dict1.keys(): # for key in dict1()
    print(key)

>>> name
age
height
hobby
location

第三种,使用values遍历字典中每个值

dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))

for value in dict1.values():
    print(value)

>>> CaiXK
38
163.1415926
['rap', 'basketball', 'python']
(34.228, 26.093)

以上就是本期的全部内容,欢迎纠错与补充,整理不易,点赞收藏关注鼓励下吧,一起进步~

相关文章:

  • 2. 深度生成模型-扩散模型(去噪扩散概率模型)
  • java6:枚举类和注解
  • webpack5(高级)
  • Python从入门到数据分析第一篇—Python简介- Python介绍与初探
  • Element-UI+Vue实现主页布局——侧边栏用户布局(上)
  • java16-多线程
  • 数据分析可视化03 技术框架:数据可视化分析的两种武器
  • 模拟实现atoi
  • Go 和 C# 的速度比较来了
  • 谷歌Guava LoadingCache介绍
  • 第二章:微服务架构构建
  • Python 基础阶段
  • 我发现凡是给offer的公司,面试时基本不问技术细节,那些问得又多又细的公司,后面就没下文了
  • 【微搭低代码】JavaScript基础知识-变量定义及初始化
  • Linux常见指令(下)
  • 【RocksDB】TransactionDB源码分析
  • 【附node操作实例】redis简明入门系列—字符串类型
  • download使用浅析
  • Git初体验
  • HTTP 简介
  • HTTP请求重发
  • java取消线程实例
  • JDK 6和JDK 7中的substring()方法
  • laravel 用artisan创建自己的模板
  • MaxCompute访问TableStore(OTS) 数据
  • mongo索引构建
  • mysql中InnoDB引擎中页的概念
  • QQ浏览器x5内核的兼容性问题
  • React Native移动开发实战-3-实现页面间的数据传递
  • Unix命令
  • zookeeper系列(七)实战分布式命名服务
  • 容器服务kubernetes弹性伸缩高级用法
  • 微信小程序上拉加载:onReachBottom详解+设置触发距离
  • 要让cordova项目适配iphoneX + ios11.4,总共要几步?三步
  • 一个SAP顾问在美国的这些年
  • #FPGA(基础知识)
  • #NOIP 2014# day.1 生活大爆炸版 石头剪刀布
  • #调用传感器数据_Flink使用函数之监控传感器温度上升提醒
  • #我与Java虚拟机的故事#连载15:完整阅读的第一本技术书籍
  • (07)Hive——窗口函数详解
  • (2)关于RabbitMq 的 Topic Exchange 主题交换机
  • (arch)linux 转换文件编码格式
  • (java)关于Thread的挂起和恢复
  • (二十一)devops持续集成开发——使用jenkins的Docker Pipeline插件完成docker项目的pipeline流水线发布
  • (附源码)计算机毕业设计ssm电影分享网站
  • (七)微服务分布式云架构spring cloud - common-service 项目构建过程
  • (转)iOS字体
  • .[backups@airmail.cc].faust勒索病毒的最新威胁:如何恢复您的数据?
  • .[hudsonL@cock.li].mkp勒索病毒数据怎么处理|数据解密恢复
  • .bat批处理(八):各种形式的变量%0、%i、%%i、var、%var%、!var!的含义和区别
  • .Net Attribute详解(上)-Attribute本质以及一个简单示例
  • .NET MAUI学习笔记——2.构建第一个程序_初级篇
  • .net Stream篇(六)
  • .net 后台导出excel ,word
  • .NET/C# 避免调试器不小心提前计算本应延迟计算的值