从具有 K 值的两个列表中呈现字典的Python程序
给定两个列表,一个用于为字典提供键,另一个用于提供值。以下程序从第二个列表中获取 K 个值并将其分配给每个键,创建以下类型的字典:
Input : test_list = [“gfg”, “best”], val_list = [1, 4, 5, 6, 7, 8, 8, 5], K = 4
Output : {‘gfg’: [1, 4, 5, 6], ‘best’: [7, 8, 8, 5]}
Explanation : Equal elements paired to each key.
Input : test_list = [“gfg”], val_list = [1, 4, 5, 6], K = 4
Output : {‘gfg’: [1, 4, 5, 6]}
Explanation : All elements assigned to only key.
方法:使用循环和切片
Python3
from collections import defaultdict
# initializing list
test_list = ["gfg", "is", "best", "good"]
# printing original list
print("The original list is : " + str(test_list))
# initializing values list
val_list = [1, 4, 5, 6, 7, 8, 8, 5, 4]
# initializing K
K = 2
# work list
val_list = val_list[:(len(test_list) * K)]
# gets required dictionary list
res = defaultdict(list)
key_cnt = 0
for idx in range(0, len(val_list)):
# append values to required keys
res[test_list[key_cnt]].append(val_list[idx])
# increment keys when K
if (idx + 1) % K == 0:
key_cnt += 1
# printing result
print("The constructed dictionary : " + str(dict(res)))
输出:
The original list is : [‘gfg’, ‘is’, ‘best’, ‘good’]
The constructed dictionary : {‘gfg’: [1, 4], ‘is’: [5, 6], ‘best’: [7, 8], ‘good’: [8, 5]}