📜  Python程序将字典及其键分成K个相等的字典

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

Python程序将字典及其键分成K个相等的字典

给定一个字典,通过划分每个键的值,将其划分为大小为 k 的相等字典列表。

方法#1:使用循环

这是可以执行此任务的方法之一。在此,我们计算每个所需键的值并将每个字典附加到字典列表中。

Python3
# Python3 code to demonstrate working of
# Divide dictionary into K equal dictionaries
# Using loop
 
# initializing dictionary
test_dict = {"Gfg": 20, "is": 36, "best": 100}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing size
K = 4
 
# constructing new dict
temp = dict()
for key in test_dict:
    temp[key] = test_dict[key] / 4
 
# creating list
res = []
for idx in range(K):
    res.append(temp)
 
# printing result
print("Required dictionary list : " + str(res))


Python3
# Python3 code to demonstrate working of
# Divide dictionary into K equal dictionaries
# Using dictionary comprehension + list comprehension
 
 
# function to divide dictionary
# and keys into K equal dictionaries
def divideDictKeys(dictionary, K):
 
    # constructing new dict
    # using dictionary comprehension
    temp = {key: test_dict[key] / K for key in test_dict}
 
    # creating list
    # using list comprehension
    res = [temp for idx in range(K)]
 
    return str(res)
 
 
# driver code
 
# initializing dictionary
test_dict = {"Gfg": 20, "is": 36, "best": 100}
 
# initializing size
K = 4
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# printing result
print("Required dictionary list : " + divideDictKeys(test_dict, K))


输出:

方法#2:使用字典理解+列表理解

这是可以执行此任务的另一种方式。在这里,我们使用字典理解形成字典,使用列表理解作为简写列表来解决这个问题。

蟒蛇3

# Python3 code to demonstrate working of
# Divide dictionary into K equal dictionaries
# Using dictionary comprehension + list comprehension
 
 
# function to divide dictionary
# and keys into K equal dictionaries
def divideDictKeys(dictionary, K):
 
    # constructing new dict
    # using dictionary comprehension
    temp = {key: test_dict[key] / K for key in test_dict}
 
    # creating list
    # using list comprehension
    res = [temp for idx in range(K)]
 
    return str(res)
 
 
# driver code
 
# initializing dictionary
test_dict = {"Gfg": 20, "is": 36, "best": 100}
 
# initializing size
K = 4
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# printing result
print("Required dictionary list : " + divideDictKeys(test_dict, K))

输出: