Python – 将列表转换为字典
有时,在处理Python记录时,我们可能会遇到问题,即我们有列表形式的数据,我们需要将某些元素分配为键和某些值以形成字典。这种类型的应用程序可以发生在数据域中。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是我们执行此任务的粗暴方式。在此,我们根据所需的切片遍历形成键值对的列表。
# Python3 code to demonstrate working of
# Convert Lists of List to Dictionary
# Using loop
# initializing list
test_list = [['a', 'b', 1, 2], ['c', 'd', 3, 4], ['e', 'f', 5, 6]]
# printing original list
print("The original list is : " + str(test_list))
# Convert Lists of List to Dictionary
# Using loop
res = dict()
for sub in test_list:
res[tuple(sub[:2])] = tuple(sub[2:])
# printing result
print("The mapped Dictionary : " + str(res))
输出 :
The original list is : [[‘a’, ‘b’, 1, 2], [‘c’, ‘d’, 3, 4], [‘e’, ‘f’, 5, 6]]
The mapped Dictionary : {(‘c’, ‘d’): (3, 4), (‘e’, ‘f’): (5, 6), (‘a’, ‘b’): (1, 2)}
方法#2:使用字典理解
这是可以执行此任务的另一种方式。这与上述方法类似,只是一种替代方案。
# Python3 code to demonstrate working of
# Convert Lists of List to Dictionary
# Using dictionary comprehension
# initializing list
test_list = [['a', 'b', 1, 2], ['c', 'd', 3, 4], ['e', 'f', 5, 6]]
# printing original list
print("The original list is : " + str(test_list))
# Convert Lists of List to Dictionary
# Using dictionary comprehension
res = {tuple(sub[:2]): tuple(sub[2:]) for sub in test_list}
# printing result
print("The mapped Dictionary : " + str(res))
输出 :
The original list is : [[‘a’, ‘b’, 1, 2], [‘c’, ‘d’, 3, 4], [‘e’, ‘f’, 5, 6]]
The mapped Dictionary : {(‘c’, ‘d’): (3, 4), (‘e’, ‘f’): (5, 6), (‘a’, ‘b’): (1, 2)}