Python – 切片直到 K 字典值列表
给定具有值作为列表的字典,将每个列表切片直到 K。
Input : test_dict = {“Gfg” : [1, 6, 3, 5, 7], “Best” : [5, 4, 2, 8, 9], “is” : [4, 6, 8, 4, 2]}, K = 3
Output : {‘Gfg’: [1, 6, 3], ‘Best’: [5, 4, 2], ‘is’: [4, 6, 8]}
Explanation : The extracted 3 length dictionary value list.
Input : test_dict = {“Gfg” : [1, 6, 3, 5, 7], “Best” : [5, 4, 2, 8, 9], “is” : [4, 6, 8, 4, 2]}, K = 2
Output : {‘Gfg’: [1, 6], ‘Best’: [5, 4], ‘is’: [4, 6]}
Explanation : The extracted 2 length dictionary value list.
方法#1:使用循环+列表切片
上述功能的组合可以用来解决这个问题。在此,我们使用切片操作执行列表切片任务并循环遍历所有键。
Python3
# Python3 code to demonstrate working of
# Slice till K dictionary value lists
# Using loop + list slicing
# initializing dictionary
test_dict = {"Gfg" : [1, 6, 3, 5, 7],
"Best" : [5, 4, 2, 8, 9],
"is" : [4, 6, 8, 4, 2]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 4
res = dict()
for sub in test_dict:
# slicing till K and reassigning
res[sub] = test_dict[sub][:K]
# printing result
print("The dictionary after conversion " + str(res))
Python3
# Python3 code to demonstrate working of
# Slice till K dictionary value lists
# Using dictionary comprehension + list slicing
# initializing dictionary
test_dict = {"Gfg" : [1, 6, 3, 5, 7],
"Best" : [5, 4, 2, 8, 9],
"is" : [4, 6, 8, 4, 2]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 4
# one-liner to slice elements of list
# items() used to get all key-value pair of dictionary
res = {key: val[:K] for key, val in test_dict.items()}
# printing result
print("The dictionary after conversion " + str(res))
The original dictionary is : {‘Gfg’: [1, 6, 3, 5, 7], ‘Best’: [5, 4, 2, 8, 9], ‘is’: [4, 6, 8, 4, 2]}
The dictionary after conversion {‘Gfg’: [1, 6, 3, 5], ‘Best’: [5, 4, 2, 8], ‘is’: [4, 6, 8, 4]}
方法#2:使用字典理解+列表切片
这是可以执行此任务的另一种方式。在此,我们使用字典理解执行重新分配的任务,并为这个问题提供了一种线性方法。
Python3
# Python3 code to demonstrate working of
# Slice till K dictionary value lists
# Using dictionary comprehension + list slicing
# initializing dictionary
test_dict = {"Gfg" : [1, 6, 3, 5, 7],
"Best" : [5, 4, 2, 8, 9],
"is" : [4, 6, 8, 4, 2]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 4
# one-liner to slice elements of list
# items() used to get all key-value pair of dictionary
res = {key: val[:K] for key, val in test_dict.items()}
# printing result
print("The dictionary after conversion " + str(res))
The original dictionary is : {‘Gfg’: [1, 6, 3, 5, 7], ‘Best’: [5, 4, 2, 8, 9], ‘is’: [4, 6, 8, 4, 2]}
The dictionary after conversion {‘Gfg’: [1, 6, 3, 5], ‘Best’: [5, 4, 2, 8], ‘is’: [4, 6, 8, 4]}