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.
Group List of Dictionary Data by Particular Key in Python can be done using itertools. groupby() method.
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.
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.
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.
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.
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