Python – 将列表转换为单个字典键值列表
有时,在使用Python列表时,我们可能会遇到需要将列表转换为字典的问题,该字典具有单个键、列表的第 K 个元素以及其他作为列表值的元素。这类问题可以在数据域中应用。让我们讨论可以执行此任务的某些方式。
Input : test_list = [6, 5, 3, 2], K = 1
Output : {5 : [6, 3, 2]}
Input : test_list = [6, 5, 3, 2], K = 2
Output : {5 : [6, 5, 2]}
方法#1:使用循环
这是可以执行此任务的方式之一。在此,我们首先创建一个键,然后附加除 K 索引之外的值以创建字典列表。
# Python3 code to demonstrate working of
# Convert list to Single Dictionary Key Value list
# Using loop
# initializing list
test_list = [5, 6, 3, 8, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# Convert list to Single Dictionary Key Value list
# Using loop
res = {test_list[K] : []}
for idx in range(len(test_list)):
if idx != K:
res[test_list[K]].append(test_list[idx])
# printing result
print("Records after conversion : " + str(res))
输出 :
The original list is : [5, 6, 3, 8, 9]
Records after conversion : {8: [5, 6, 3, 9]}
方法#2:使用列表切片
这是可以执行此任务的又一班轮。在此,我们在第 K 个索引上切出列表并分配为字典中的值。
# Python3 code to demonstrate working of
# Convert list to Single Dictionary Key Value list
# Using loop
# initializing list
test_list = [5, 6, 3, 8, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# Convert list to Single Dictionary Key Value list
# Using loop
res = {test_list[K] : test_list[:K] + test_list[K + 1:]}
# printing result
print("Records after conversion : " + str(res))
输出 :
The original list is : [5, 6, 3, 8, 9]
Records after conversion : {8: [5, 6, 3, 9]}