首页 > 文章列表 > Python程序将字典及其键分成K个相等的字典

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

Python 字典 分割
352 2023-09-14

字典是一种独特的数组形式,用于在Python中实现数据结构。字典有几个相关的特性,使其成为 Python 中非常强大的工具。它以键值对的形式存储数据,其中每个键都是唯一标识符,用于访问与其关联的相应值。

我们可以对该字典执行多种操作并操作其中存储的数据。本文将解释这样一个操作,我们将字典及其键分成 K 个相等的字典。

理解问题

我们必须传递一个字典,然后将其分成 K 个相等的字典,其中“K”是原始字典的大小。划分的方式应该是平均划分所有键。让我们通过一个例子来理解这一点 -

Input: dict1 = {"Score":100, "Age": 40, "Salary": 25000, "cutoff":44}
Output: [{'Score': 25.0, 'Age': 10.0, 'Salary': 6250.0, 'cutoff': 11.0}, 
{'Score': 25.0, 'Age': 10.0, 'Salary': 6250.0, 'cutoff': 11.0}, 
{'Score': 25.0, 'Age': 10.0, 'Salary': 6250.0, 'cutoff': 11.0}, 
{'Score': 25.0, 'Age': 10.0, 'Salary': 6250.0, 'cutoff': 11.0}]

这里与不同键关联的每个值都减少到原始值的 1/K 倍,并返回 K 个字典的列表。现在我们已经讨论了问题陈述,让我们讨论一些解决方案。

使用迭代

在这种方法中,我们将传递一个示例字典,然后借助“len()”方法获取“K”值。该方法将返回字典的长度。之后,我们将迭代示例字典并借助“/”操作数将每个“键值” 除以 K。

我们将把这些划分后的值存储在一个空字典中,然后借助“append()”方法将所有新创建的字典添加到一个空列表中。

示例

dict1 = {"Score":100 , "Age": 40, "Salary": 25000, "cutoff":44}
print(f"Original dictionary is: {dict1}")
K = len(dict1)
print(f"The value for K is: {K}")

empLis = []
empDict ={}
for keys in dict1:
   empDict[keys] = dict1[keys]/K
   empLis.append(empDict)

print(f"The newly divided dictionary is: {empLis}")

输出

Original dictionary is: {'Score': 100, 'Age': 40, 'Salary': 25000, 'cutoff': 44}
The value for K is: 4
The newly divided dictionary is: [{'Score': 25.0, 'Age': 10.0, 'Salary': 6250.0, 'cutoff': 11.0}, {'Score': 25.0, 'Age': 10.0, 'Salary': 6250.0, 'cutoff': 11.0}, {'Score': 25.0, 'Age': 10.0, 'Salary': 6250.0, 'cutoff': 11.0}, {'Score': 25.0, 'Age': 10.0, 'Salary': 6250.0, 'cutoff': 11.0}]

使用列表理解和字典理解

此方法是先前解决方案的优化版本。在这里,我们将借助字典理解和列表理解来总结单个字典和列表中的迭代。传递示例字典后,我们将创建一个字典,在其中存储划分后的值 (DivDict)。

进行迭代并返回原始字典除以 K 的键。列表 (lisDict) 存储包含除后值的 K 个字典。我们指定列表的长度等于 K 值。

示例

dict1 = {"Number of sixes":244, "Number of fours": 528, "Strike rate": 164, "Balls faced":864}
print(f"Original dictionary is: {dict1}")
K = len(dict1)
print(f"The value for K is: {K}")

#using dictionary comprehension
DivDict ={key_value:dict1[key_value]/K for key_value in dict1}
#using list comprehension
lisDict = [DivDict for i in range(K)]

print(f"The newly divided dictionary is: {lisDict}")

输出

Original dictionary is: {'Number of sixes': 244, 'Number of fours': 528, 'Strike rate': 164, 'Balls faced': 864}
The value for K is: 4
The newly divided dictionary is: [{'Number of sixes': 61.0, 'Number of fours': 132.0, 'Strike rate': 41.0, 'Balls faced': 216.0}, {'Number of sixes': 61.0, 'Number of fours': 132.0, 'Strike rate': 41.0, 'Balls faced': 216.0}, {'Number of sixes': 61.0, 'Number of fours': 132.0, 'Strike rate': 41.0, 'Balls faced': 216.0}, {'Number of sixes': 61.0, 'Number of fours': 132.0, 'Strike rate': 41.0, 'Balls faced': 216.0}]

还有其他方法涉及使用以下方法: - zip()、lambda()、groupby()、切片等。

当我们必须在代码中引入某些规范(例如针对字典中的特定值或键)时,可以使用这些方法。上述解决方案是可用于将样本字典分成 K 个相等部分的基本方法。

结论

在本文中,我们讨论了将字典及其键划分为 K 个相等的字典 的两种解决方案。第一个解决方案围绕“循环概念”,我们迭代字典并将其添加到列表中。第二个解决方案侧重于更优化的方法,我们将整个循环概念总结为单个字典和列表。