打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
数据分析:python dict字典数据处理技巧!

众所周知,在python编程过程中对于同一个业务的处理往往有很多种的处理方式,今天探讨如何在python中更加优雅的处理字典数据?

本文将介绍高级 Python 工程师常用的 dict 操作技巧,希望能够给大家一些新的想法。

自从python解释器版本升级到3.9以后对于语法方面也取得了比较的优化,比如使用一个简单的联合符号就能够将两个字典dict进行合并。

# Creating a dictionary with two keys, 姓名 and 年龄, and two values, Python 集中营 and 21.
code_1 = {'姓名''Python 集中营''年龄''21'}

# Creating a dictionary with two keys, 成绩 and 表现, and two values, 99 and 优秀.
code_2 = {'成绩''99''表现''优秀'}

# Merging two dictionaries.
code_ = code_1 | code_2

# Printing the merged dictionary.
print(code_)

# {'姓名': 'Python 集中营', '年龄': '21', '成绩': '99', '表现': '优秀'}

也可以直接使用|=将第一个字典和第二个字典合并到第一个字典中进行合并。

# Merging the two dictionaries.
code_1 |= code_2

# Printing the merged dictionary.
print(code_1)

# {'姓名': 'Python 集中营', '年龄': '21', '成绩': '99', '表现': '优秀'}

另外若是一些老版本的python字典合并可以使用**的联合符号来合并。

# Merging the two dictionaries.
code_ = {**code_1, **code_2}

# Printing the merged dictionary.
print(code_)

# {'姓名': 'Python 集中营', '年龄': '21', '成绩': '99', '表现': '优秀'}

最后一个比较有用的就是字典dict的列表推导式的应用,比如需要根据python列表list创建一个字典。

使用下面的推导式初始化字典,必须保证两个list列表的值数量是一致的。

# Creating a list of column names.
columns_ = ['姓名''年龄''班级''表现']

# Creating a list of values.
values_ = ['Python 集中营''21''2110''优秀']

# Creating a dictionary with the keys from `columns_` and the values from `values_`.
codes_ = {column_: value_ for column_, value_ in zip(columns_, values_)}

# Printing the dictionary.
print(codes_)

# {'姓名': 'Python 集中营', '年龄': '21', '班级': '2110', '表现': '优秀'}

「Python 集中营」,只做知识分享 !

如何使用Selenium IDE浏览器插件轻松完成脚本录制,轻松搞定自动化测试!

使用python一起进入新年倒计时吧,可直接打包成exe应用!

知识记录:python如何通过反射机制处理对象?

PyQt5干货:如何实现进度条与定时器及子线程的同步关联!

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Python 字典(Dictionary)详解
【编程课堂】有序字典 OrderedDict
Python 字典(Dictionary) | 菜鸟教程
python之dictionary
如何在 Python 中检查字典中是否存在某个键 – Python Dict Has Key
第14天python字典常用内置函数资料详解,今天就学1小时
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服