📜  Python|将字典添加到元组

📅  最后修改于: 2022-05-13 01:54:20.190000             🧑  作者: Mango

Python|将字典添加到元组

有时,在处理数据时,我们可能会遇到一个问题,即我们需要向元组追加一条Python字典形式的新记录。在复合属性的情况下,这种应用程序可以进入 Web 开发领域。让我们讨论可以执行此任务的某些方式。
方法 #1:使用 list() + append + tuple()
这个方法可以用来解决这个问题。在这种情况下,我们只需将元组转换为列表,然后执行列表追加,然后使用 tuple() 将列表重新转换为元组。

例子 :

Python3
# Python3 code to demonstrate working of
# Add dictionary to tuple
# using append() + tuple() + list comprehension
 
# initialize tuple
test_tup = (4, 5, 6)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# initialize dictionary
test_dict = {"gfg" : 1, "is" : 2, "best" : 3}
 
# Add dictionary to tuple
# using append() + tuple() + list comprehension
test_tup = list(test_tup)
test_tup.append(test_dict)
test_tup = tuple(test_tup)
 
# printing result
print("Tuple after addition of dictionary : " + str(test_tup))


Python3
# Python3 code to demonstrate working of
# Add dictionary to tuple
# using + operator
 
# initialize tuple
test_tup = (4, 5, 6)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# initialize dictionary
test_dict = {"gfg" : 1, "is" : 2, "best" : 3}
 
# Add dictionary to tuple
# using + operator
res = test_tup + (test_dict, )
 
# printing result
print("Tuple after addition of dictionary : " + str(res))


输出 :
The original tuple : (4, 5, 6)
Tuple after addition of dictionary : (4, 5, 6, {'best': 3, 'is': 2, 'gfg': 1})


方法 #2:使用 +运算符
这是执行此任务的另一种方式。在此,我们将字典添加到不同的元组,然后将旧元组添加到该元组并形成新元组。关键区别在于这不是就地加法作为上层方法,而是从旧元组中创建新元组。

例子 :

Python3

# Python3 code to demonstrate working of
# Add dictionary to tuple
# using + operator
 
# initialize tuple
test_tup = (4, 5, 6)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# initialize dictionary
test_dict = {"gfg" : 1, "is" : 2, "best" : 3}
 
# Add dictionary to tuple
# using + operator
res = test_tup + (test_dict, )
 
# printing result
print("Tuple after addition of dictionary : " + str(res))
输出 :
The original tuple : (4, 5, 6)
Tuple after addition of dictionary : (4, 5, 6, {'best': 3, 'is': 2, 'gfg': 1})