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;
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.
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.
That means the dictionary cannot have two items with the same key; hence, dictionary keys are immutable.
zip() can accept any type of iterable, such as files, lists, tuples, dictionaries, sets, and so on.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With