Python program to divide dictionary and its keys into K equal dictionaries

Python program to divide dictionary and its keys into K equal dictionaries

Let's create a Python program that divides a dictionary and its keys into K approximately equal dictionaries.

Objective:

Given a dictionary and an integer K, divide the dictionary into K dictionaries such that each new dictionary contains roughly the same number of key-value pairs. If the total number of keys in the dictionary is not exactly divisible by K, some dictionaries will have one more key-value pair than others.

Example:

For the dictionary:

{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} 

and K=2,

The result will be:

[{'a': 1, 'b': 2, 'c': 3}, {'d': 4, 'e': 5}] 

Python Program:

def divide_dict(data, K): # Calculate size of each chunk n = len(data) chunk_size = n // K remainder = n % K # Convert dictionary to list of items for slicing items = list(data.items()) divided_dicts = [] start = 0 for i in range(K): end = start + chunk_size # Distribute remainder among the first few chunks if remainder: end += 1 remainder -= 1 # Convert sliced items back to dictionary and append to result divided_dicts.append(dict(items[start:end])) start = end return divided_dicts # Test the function sample_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} K = 2 result = divide_dict(sample_dict, K) # Print the results print(f"Original Dictionary: {sample_dict}") print(f"Divided into {K} dictionaries: {result}") 

When you run the program, you'll get:

Original Dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} Divided into 2 dictionaries: [{'a': 1, 'b': 2, 'c': 3}, {'d': 4, 'e': 5}] 

Explanation:

  1. We first calculate the size of each chunk using integer division.
  2. The remainder tells us how many of the divided dictionaries will have an extra key-value pair.
  3. We then convert the dictionary into a list of key-value pairs for easy slicing.
  4. We iterate K times, creating a new dictionary in each iteration. If there's any remainder, we add an extra key-value pair to the current dictionary and decrement the remainder.
  5. The result is a list of K approximately equal dictionaries.

This method efficiently divides a given dictionary into K approximately equal parts.


More Tags

command-line-interface file-get-contents screen-recording swiftmailer app-startup iconbutton public-key-encryption csproj translate3d dynamic-jasper

More Programming Guides

Other Guides

More Programming Examples