首页 > 编程知识 正文

Python 程序:将元组转换为字典

时间:2023-11-25 09:12:55 阅读:309038 作者:GUFK

编写一个 Python 程序,将 Tuple 项转换成字典。在 Python 中,我们可以使用 dict 函数将元组转换为字典。默认情况下,它将第一项指定为关键字,第二项指定为字典值。

# Convert Tuple to Dictionary

tup = ((1, 'x'), (2, 'y'), (3, 'z'))
print(tup)
print("Data Type = ", type(tup))

tupToDict = dict(tup)
print(tupToDict)
print("Data Type = ", type(tupToDict))

使用 for 循环将元组转换为字典的 Python 程序。

通过使用 for 循环,我们可以根据需要更改字典键和值。例如,在第二个示例中,我们将键替换为值。

# Convert Tuple to Dictionary

tup = ((1, 'x'), (2, 'y'), (3, 'z'))
print(tup)

tupToDict1 = dict((key, value) for key, value in tup)
print(tupToDict1)
print("Data Type = ", type(tupToDict1))

tupToDict2 = dict((key, value) for value, key in tup)
print(tupToDict2)
print("Data Type = ", type(tupToDict2))

tupToDict3 = dict()
for key, value in tup:
    tupToDict3[key] =  value

print(tupToDict3)
print("Data Type = ", type(tupToDict3))
((1, 'x'), (2, 'y'), (3, 'z'))
{1: 'x', 2: 'y', 3: 'z'}
Data Type =  <class 'dict'>
{'x': 1, 'y': 2, 'z': 3}
Data Type =  <class 'dict'>
{1: 'x', 2: 'y', 3: 'z'}
Data Type =  <class 'dict'>

在这个 Python 例子中,我们使用了字典、映射函数将元组转换为字典。在这里,反转功能会将键反转或更改为值,反之亦然。第二个示例使用 slice 选项将所有元组项复制或转换为字典。在第三个将元组转换为字典的示例中,我们使用了一个负数作为切片(dict(I[:-1]表示 tup 中的 I))来更改字典键和值。

# Convert Tuple to Dictionary

tup = ((1, 'USA'), (2, 'UK'), (3, 'France'), (4, 'Germany'))
print(tup)

tupToDict1 = dict(map(reversed, tup))
print(tupToDict1)
print()

tupToDict2 = dict(i[::1] for i in tup)
print(tupToDict2)
print()

tupToDict3 = dict(i[::-1] for i in tup)
print(tupToDict3)
((1, 'USA'), (2, 'UK'), (3, 'France'), (4, 'Germany'))
{'USA': 1, 'UK': 2, 'France': 3, 'Germany': 4}

{1: 'USA', 2: 'UK', 3: 'France', 4: 'Germany'}

{'USA': 1, 'UK': 2, 'France': 3, 'Germany': 4}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。