Python – 从前后键值构建字典
给定一个列表,使用键作为前半部分值和从最后开始的值构造字典。
Input : test_list = [4, 10, 5, 3]
Output : {4: 3, 10: 5}
Explanation : First (4) is paired with rear (3) and so on.
Input : test_list = [5, 3]
Output : {5: 3}
Explanation : First (5) is paired with rear (3).
Input : test_dict = {“Apple” : 2, “Mango” : 2, “Grapes” : 2}, {“Apple” : 2, “Mango” : 2, “Grapes” : 2}
Output : 12
Explanation : (2*2) + (2*2) + (2*2) = 12.
Input : test_dict = {“Apple” : 3, “Mango” : 2, “Grapes” : 3}, {“Apple” : 2, “Mango” : 2, “Grapes” : 2}
Output : 16
Explanation : The summation of product leads to 16 as above.
方法#1:使用循环
这是可以执行此任务的粗暴方式。在此,我们从头开始运行一个循环,从 beg-end 中提取值,并相应地构造键值映射。
Python3
# Python3 code to demonstrate working of
# Dictionary construction from front-rear key values
# Using loop
# initializing list
test_list = [4, 6, 3, 10, 5, 3]
# printing original list
print("The original list : " + str(test_list))
# initializing size and empty Dictionary
n = len(test_list)
res = dict()
# running loop till mid
for idx in range(n // 2):
# mapping as required
res.__setitem__(test_list[idx], test_list[n - idx - 1])
# printing result
print("The mapped dictionary : " + str(res))
Python3
# Python3 code to demonstrate working of
# Dictionary construction from front-rear key values
# Using zip() + dict()
# initializing list
test_list = [4, 6, 3, 10, 5, 3]
# printing original list
print("The original list : " + str(test_list))
# using zip to cut first and second half
n = len(test_list)
res = dict(zip(test_list[:n // 2], test_list[n // 2:][::-1]))
# printing result
print("The mapped dictionary : " + str(res))
The original list : [4, 6, 3, 10, 5, 3]
The mapped dictionary : {4: 3, 6: 5, 3: 10}
方法#2:使用 zip() + dict()
这是可以执行此任务的另一种方式。在此,我们使用 zip() 执行压缩键和值元素的任务,并使用 dict() 将结果转换为字典。
Python3
# Python3 code to demonstrate working of
# Dictionary construction from front-rear key values
# Using zip() + dict()
# initializing list
test_list = [4, 6, 3, 10, 5, 3]
# printing original list
print("The original list : " + str(test_list))
# using zip to cut first and second half
n = len(test_list)
res = dict(zip(test_list[:n // 2], test_list[n // 2:][::-1]))
# printing result
print("The mapped dictionary : " + str(res))
The original list : [4, 6, 3, 10, 5, 3]
The mapped dictionary : {4: 3, 6: 5, 3: 10}