Python 程序将元组转换为字典

编写一个 Python 程序,将元组项转换为字典。在此编程语言中,我们可以使用 dict 函数将元组转换为字典。默认情况下,它会将第一个项作为键,第二个项作为字典值。

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

tupToDict = dict(tup)
print(tupToDict)
print("Data Type = ", type(tupToDict))
Program to Convert Tuple to Dictionary

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

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

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'>

在此示例中,我们使用 dictmap 函数将元组转换为字典。这里,reversed 函数将反转或更改键和值。第二个示例使用切片选项将所有元组项复制或转换为字典。

在第三个将元组转换为字典的示例中,我们使用了负数作为切片(dict(i[::-1] for i in tup))来更改字典的键和值。

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}