📜  Python - 调整字典中的键大小

📅  最后修改于: 2022-05-13 01:54:20.682000             🧑  作者: Mango

Python - 调整字典中的键大小

给定字典,通过从键中获取 k 个元素来将键的大小调整为 K。

方法#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))


输出:

方法#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))

输出: