众所周知,在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 集中营」,只做知识分享 !
联系客服