How to use 'python sum dictionary values by key' in Python

Every line of 'python sum dictionary values by key' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
29def count_value(lst, key):
30 d = {}
31 for obj in lst:
32 val = obj[key]
33 if val in d:
34 d[val] = d[val] + 1
35 else:
36 d[val] = 1
37 return d.iteritems()
600def sum_dict(self, dictionary):
601 '''This method returns the sum of all values within a
602 nested dictionary that can contain float numbers
603 and/or other dictionaries containing the same type
604 of elements. It works in a recursive way.
605
606 Parameters
607 ----------
608 dictionary: dict or float
609 dictionary containing other dictionaries and/or
610 float numbers. If it's a float it will return
611 its value directly
612
613 Returns
614 -------
615 val: float
616 value of the sum of all values within the
617 nested dictionary
618
619 '''
620
621 # Initialize the sum
622 val=0.
623 # If dictionary is a float we have arrived to an
624 # end point and we want to return its value
625 if isinstance(dictionary, float):
626
627 return dictionary
628
629 # If dictionary is still a dictionary we should
630 # keep searching for an end point with a float
631 elif isinstance(dictionary, dict):
632 for k in dictionary.keys():
633 # Sum the values within this dictionary
634 val += self.sum_dict(dictionary=dictionary[k])
635
636 return val

Related snippets