Python – 将记录列表转换为分隔字典
有时,在处理Python记录时,我们可能会遇到一个问题,我们需要将元组记录的每个元素转换为字典中的单独键,每个索引具有不同的值。这类问题可以在数据域中应用。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是解决这个问题的方法之一。在此,我们迭代元组列表并将所需的值分配给新构建的字典的每个键。
# Python3 code to demonstrate working of
# Convert Records List to Segregated Dictionary
# Using loop
# initializing list
test_list = [(1, 2), (3, 4), (5, 6)]
# printing original list
print("The original list is : " + str(test_list))
# initializing index value
frst_idx = "Gfg"
scnd_idx = 'best'
# Convert Records List to Segregated Dictionary
# Using loop
res = dict()
for sub in test_list:
res[sub[0]] = frst_idx
res[sub[1]] = scnd_idx
# printing result
print("The constructed Dictionary list : " + str(res))
输出 :
The original list is : [(1, 2), (3, 4), (5, 6)]
The constructed Dictionary list : {1: ‘Gfg’, 2: ‘best’, 3: ‘Gfg’, 4: ‘best’, 5: ‘Gfg’, 6: ‘best’}
方法 #2:使用zip() + chain() + cycle()
+ 列表理解
上述功能的组合可用于执行此任务。在此,我们使用 chain() 解包值,然后交替循环要初始化的值,然后使用 zip() 压缩回值。
# Python3 code to demonstrate working of
# Convert Records List to Segregated Dictionary
# Using zip() + chain() + cycle() + list comprehension
from itertools import chain, cycle
# initializing list
test_list = [(1, 2), (3, 4), (5, 6)]
# printing original list
print("The original list is : " + str(test_list))
# initializing index value
frst_idx = "Gfg"
scnd_idx = 'best'
# Convert Records List to Segregated Dictionary
# Using zip() + chain() + cycle() + list comprehension
res = dict(zip(chain(*test_list), cycle([frst_idx, scnd_idx])))
# printing result
print("The constructed Dictionary list : " + str(res))
输出 :
The original list is : [(1, 2), (3, 4), (5, 6)]
The constructed Dictionary list : {1: ‘Gfg’, 2: ‘best’, 3: ‘Gfg’, 4: ‘best’, 5: ‘Gfg’, 6: ‘best’}