Python – 将嵌套元组转换为自定义键字典
有时,在处理Python记录时,我们可能会得到没有正确列名/标识符的数据,这些数据只能通过它们的索引来识别,但我们打算为它们分配键并以字典的形式呈现。这类问题可以应用在 Web 开发等领域。让我们讨论可以执行此任务的某些方式。
Input : test_tuple = ((1, ‘Gfg’, 2), (3, ‘best’, 4)), keys = [‘key’, ‘value’, ‘id’]
Output : [{‘key’: 1, ‘value’: ‘Gfg’, ‘id’: 2}, {‘key’: 3, ‘value’: ‘best’, ‘id’: 4}]
Input : test_tuple = test_tuple = ((1, ‘Gfg’), (2, 3)), keys = [‘key’, ‘value’]
Output : [{‘key’: 1, ‘value’: ‘Gfg’}, {‘key’: 2, ‘value’: 3}]
方法#1:使用列表理解+字典理解
上述功能的组合可以用来解决这个问题。在此,我们执行使用字典理解分配键和所有键的迭代以及使用列表理解构造数据的任务。
# Python3 code to demonstrate working of
# Convert Nested Tuple to Custom Key Dictionary
# Using list comprehension + dictionary comprehension
# initializing tuple
test_tuple = ((4, 'Gfg', 10), (3, 'is', 8), (6, 'Best', 10))
# printing original tuple
print("The original tuple : " + str(test_tuple))
# Convert Nested Tuple to Custom Key Dictionary
# Using list comprehension + dictionary comprehension
res = [{'key': sub[0], 'value': sub[1], 'id': sub[2]}
for sub in test_tuple]
# printing result
print("The converted dictionary : " + str(res))
The original tuple : ((4, ‘Gfg’, 10), (3, ‘is’, 8), (6, ‘Best’, 10))
The converted dictionary : [{‘key’: 4, ‘value’: ‘Gfg’, ‘id’: 10}, {‘key’: 3, ‘value’: ‘is’, ‘id’: 8}, {‘key’: 6, ‘value’: ‘Best’, ‘id’: 10}]
方法 #2:使用zip()
+ 列表理解
上述功能的组合可以用来解决这个问题。在此,我们使用列表内容分配索引键并使用 zip() 进行映射。在此,提供了预定义/缩放键的灵活性。
# Python3 code to demonstrate working of
# Convert Nested Tuple to Custom Key Dictionary
# Using zip() + list comprehension
# initializing tuple
test_tuple = ((4, 'Gfg', 10), (3, 'is', 8), (6, 'Best', 10))
# printing original tuple
print("The original tuple : " + str(test_tuple))
# initializing Keys
keys = ['key', 'value', 'id']
# Convert Nested Tuple to Custom Key Dictionary
# Using zip() + list comprehension
res = [{key: val for key, val in zip(keys, sub)}
for sub in test_tuple]
# printing result
print("The converted dictionary : " + str(res))
The original tuple : ((4, ‘Gfg’, 10), (3, ‘is’, 8), (6, ‘Best’, 10))
The converted dictionary : [{‘key’: 4, ‘value’: ‘Gfg’, ‘id’: 10}, {‘key’: 3, ‘value’: ‘is’, ‘id’: 8}, {‘key’: 6, ‘value’: ‘Best’, ‘id’: 10}]