I have a dictionary of (string, decimal) and need to calculate the sum of all the Values (decimal values) starting from the second item. Is it achievable using LINQ?
You can get a generator of all the values in the dictionary, then cast it to a list and use the sum() function to get the sum of all the values.
To sum all values in a Python dictionary, use sum() and a list representation of the dictionary values obtained with my_dict. values() and using list() for the conversion.
In python, if we want a dictionary in which one key has multiple values, then we need to associate an object with each key as value. This value object should be capable of having various values inside it. We can either use a tuple or a list as a value in the dictionary to associate multiple values with a key.
Very achievable using LINQ:
myDict.Skip(1).Sum(x => x.Value);
However, the standard Dictionary
class doesn't guarantee ordering of items, so the "first" item can be anything.
Why not just sum them all up, then subtract the first item?
myList.Sum(x => x.Value) - myList.First().Value;
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