我们可以对该字典执行多种操作并操作其中存储的数据。本文将解释这样一个操作,我们将字典及其键分成 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(foriginal dictionary is: {dict1})k = len(dict1)print(fthe value for k is: {k})emplis = []empdict ={}for keys in dict1: empdict[keys] = dict1[keys]/k emplis.append(empdict)print(fthe newly divided dictionary is: {emplis})
输出original dictionary is: {'score': 100, 'age': 40, 'salary': 25000, 'cutoff': 44}the value for k is: 4the 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(foriginal dictionary is: {dict1})k = len(dict1)print(fthe value for k is: {k})#using dictionary comprehensiondivdict ={key_value:dict1[key_value]/k for key_value in dict1}#using list comprehensionlisdict = [divdict for i in range(k)]print(fthe 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: 4the 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 个相等的字典 的两种解决方案。第一个解决方案围绕“循环概念”,我们迭代字典并将其添加到列表中。第二个解决方案侧重于更优化的方法,我们将整个循环概念总结为单个字典和列表。
以上就是python程序将字典及其键分成k个相等的字典的详细内容。
