在 Python 中将字典转换为元组列表
在 Python 里,从一种集合类型转换成另一个集合类型是很常见的。根据数据处理的需求,我们可能必须转换字典中成对的键值对,将其转换成列表中表示元组的对。在这篇文章中,我们将了解实现此目的的方法。
使用 in
这是一个直接的方法,只需考虑
示例
Adict = {30:'Mon',11:'Tue',19:'Fri'}
# Given dictionary
print("The given dictionary: ",Adict)
# Using in
Alist = [(key, val) for key, val in Adict.items()]
# Result
print("The list of tuples: ",Alist)输出
运行以上代码,会得到以下结果 −
The given dictionary: {30: 'Mon', 11: 'Tue', 19: 'Fri'}
The list of tuples: [(30, 'Mon'), (11, 'Tue'), (19, 'Fri')]使用 zip
zip 函数将传给它的项作为参数合并起来。因此,我们取字典的键和值作为 zip 函数的参数,并将结果放在一个列表函数之下。键值对变成了列表的元组。
示例
Adict = {30:'Mon',11:'Tue',19:'Fri'}
# Given dictionary
print("The given dictionary: ",Adict)
# Using zip
Alist = list(zip(Adict.keys(), Adict.values()))
# Result
print("The list of tuples: ",Alist)输出
运行以上代码,会得到以下结果 −
The given dictionary: {30: 'Mon', 11: 'Tue', 19: 'Fri'}
The list of tuples: [(30, 'Mon'), (11, 'Tue'), (19, 'Fri')]使用 append
在此方法中,我们取一个空列表,并将每一对键值以元组方式附加。设计一个 for 循环来将键值对转换成元组。
示例
Adict = {30:'Mon',11:'Tue',19:'Fri'}
# Given dictionary
print("The given dictionary: ",Adict)
Alist = []
# Uisng append
for x in Adict:
k = (x, Adict[x])
Alist.append(k)
# Result
print("The list of tuples: ",Alist)输出
运行以上代码,会得到以下结果 −
The given dictionary: {30: 'Mon', 11: 'Tue', 19: 'Fri'}
The list of tuples: [(30, 'Mon'), (11, 'Tue'), (19, 'Fri')]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP