Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GroupBy a Dictionary based on key

Tags:

c#

group-by

I have a Dictionary<string,string> that I want to group. Here are some sample key/value pairs

==========================
| Key            | Value |
==========================
| A_FirstValue   | 1     |
| A_SecondValue  | 2     |
| B_FirstValue   | 1     |
| B_SecondValue  | 2     |
==========================

Now, I want to group it according to the first letter or word in the key before the first instance of the character '_'

So, the final result will be Dictionary<string, Dictionary<string, string>>. For the example above the result will be:

A -> A_FirstValue, 1
     A_SecondValue, 2

B -> B_FirstValue, 1
     B_SecondValue, 2

Is this even possible? Anyone who could help me please?

Thanks.

like image 758
Lemuel Nitor Avatar asked May 09 '12 13:05

Lemuel Nitor


People also ask

How do you group dictionary using keys?

Group List of Dictionary Data by Particular Key in Python can be done using itertools. groupby() method.

How do you grab a value from a dictionary?

You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist. Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.

How do I fetch a dictionary value?

Python dictionary | values() values() is an inbuilt method in Python programming language that returns a view object. The view object contains the values of the dictionary, as a list. If you use the type() method on the return value, you get “dict_values object”. It must be cast to obtain the actual list.

Can tuple be key for dictionary?

A tuple can never be used as a key in a dictionary. Answer: False. A tuple can be used as a key so long as all of its elements are immutable. 12.


1 Answers

Well, you could use:

var dictionary = dictionary.GroupBy(pair => pair.Key.Substring(0, 1))
       .ToDictionary(group => group.Key,
                     group => group.ToDictionary(pair => pair.Key,
                                                 pair => pair.Value));

The group part will give you an IGrouping<string, KeyValuePair<string, string>>, and the subsequent ToDictionary will convert each group of key/value pairs back into a dictionary.

EDIT: Note that this will always use the first letter. For anything more complicated, I would probably write a separate ExtractFirstWord(string) method and call that in the GroupBy lambda expression.

like image 83
Jon Skeet Avatar answered Sep 21 '22 01:09

Jon Skeet