Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split dictionary into multiple equal sized dictionaries

I have a Dictionary shown below. Say there are 400 elements in the Dictionary I want to split this Dictionary into 4 equal sized dictionaries. How do I do this? With list there is a range method that I can use however not sure what to do here?

I do not care how the Dictionary is split just so that they are equally sized.

Dictionary<string, CompanyDetails> coDic;
like image 724
mHelpMe Avatar asked May 12 '15 11:05

mHelpMe


People also ask

How do you split a dictionary into two in python?

Method 1: Split dictionary keys and values using inbuilt functions. Here, we will use the inbuilt function of Python that is . keys() function in Python, and . values() function in Python to get the keys and values into separate lists.

Can you divide dictionary in python?

To divide each value in a dictionary by a total value:Use a dict comprehension to iterate over the dictionary's items. On each iteration, divide the current value by the total. The new dictionary will contain the division results.

Can two dictionaries have same keys?

That means the dictionary cannot have two items with the same key; hence, dictionary keys are immutable.

Can you zip dictionaries?

zip() can accept any type of iterable, such as files, lists, tuples, dictionaries, sets, and so on.


2 Answers

I would use the following query:

Dictionary<string, CompanyDetails>[] result =
    dict
        .Select((kvp, n) => new { kvp, k = n % 4 })
        .GroupBy(x => x.k, x => x.kvp)
        .Select(x => x.ToDictionary(y => y.Key, y => y.Value))
        .ToArray();

The advantage here is the avoidance of closing over a counter as the .Select((kvp, n) => ...) statement has a counter built-in.

like image 50
Enigmativity Avatar answered Oct 20 '22 17:10

Enigmativity


You can use a simple modulus to group the dictionary in parts:

int numberOfGroups = 4;
int counter = 0;

var result = dict.GroupBy(x => counter++ % numberOfGroups);

The modulus (%) makes the GroupBy to be restricted to a number in the range 0..3 (actually 0..numberOfGroups - 1). This will make the grouping for you.

A problem though with this one is that it doesn't preserve the order. This one does:

decimal numberOfGroups = 4;
int counter = 0;
int groupSize = Convert.ToInt32(Math.Ceiling(dict.Count / numberOfGroups));

var result = dict.GroupBy(x => counter++ / groupSize);
like image 30
Patrick Hofman Avatar answered Oct 20 '22 15:10

Patrick Hofman