Python - 调整字典中的键大小
给定字典,通过从键中获取 k 个元素来将键的大小调整为 K。
Input : test_dict = {“geeksforgeeks” :3, “best” :3, “coding” :4, “practice” :3}, K = 3
Output : {‘gee’: 3, ‘bes’: 3, ‘cod’: 4, ‘pra’: 3}
Explanation : Keys resized to have 3 elements.
Input : test_dict = {“geeksforgeeks” :3, “best” :3, “coding” :4, “practice” :3}, K = 4
Output : {‘geek’: 3, ‘best’: 3, ‘codi’: 4, ‘prac’: 3}
Explanation : Keys resized to have 4 elements.
方法#1:使用切片+循环
在这种情况下,调整大小是使用字典键的切片完成的,循环用于迭代字典的所有键。
Python3
# Python3 code to demonstrate working of
# Resize Keys in dictionary
# Using slicing + loop
# initializing dictionary
test_dict = {"geeksforgeeks": 3, "best": 3, "coding": 4, "practice": 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 2
# reforming dictionary
res = dict()
for key in test_dict:
# resizing to K prefix keys
res[key[:K]] = test_dict[key]
# printing result
print("The required result : " + str(res))
Python3
# Python3 code to demonstrate working of
# Resize Keys in dictionary
# Using dictionary comprehension + slicing
# initializing dictionary
test_dict = {"geeksforgeeks": 3, "best": 3, "coding": 4, "practice": 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 2
# reforming dictionary
res = {key[:K]: test_dict[key] for key in test_dict}
# printing result
print("The required result : " + str(res))
输出:
The original dictionary is : {‘geeksforgeeks’: 3, ‘best’: 3, ‘coding’: 4, ‘practice’: 3}
The required result : {‘ge’: 3, ‘be’: 3, ‘co’: 4, ‘pr’: 3}
方法#2:使用字典理解+切片
在此,我们使用字典理解在一个 liner 中执行字典重整任务。
蟒蛇3
# Python3 code to demonstrate working of
# Resize Keys in dictionary
# Using dictionary comprehension + slicing
# initializing dictionary
test_dict = {"geeksforgeeks": 3, "best": 3, "coding": 4, "practice": 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing K
K = 2
# reforming dictionary
res = {key[:K]: test_dict[key] for key in test_dict}
# printing result
print("The required result : " + str(res))
输出:
The original dictionary is : {‘geeksforgeeks’: 3, ‘best’: 3, ‘coding’: 4, ‘practice’: 3}
The required result : {‘ge’: 3, ‘be’: 3, ‘co’: 4, ‘pr’: 3}