How to sum all the values in a dictionary?
As you'd expect:
sum(d.values())
How to sum dict elements
A little ugly, but a one-liner:
dictf = reduce(lambda x, y: dict((k, v + y[k]) for k, v in x.iteritems()), dict1)
Python: Sum of certain values of a dictionary
You will get that error because the value
changes as per its iterator. Inorder to find the sum you need to store and add the values to another variable and then call sum()
or you could add it to a new variable.
What the sum()
does is take a list and iterate through it. In your code what it is doing is passing the current value in the loop only so 1 value.
Example: Note (There are many ways to do this.)
name = "ABC"
sum = 0
for character in name:
for key, value in dict.items():
if key == character:
print(value)
sum = value + sum
print(sum)
Python - sum values in dictionary
sum(item['gold'] for item in myList)
How to sum values in multidimensional dictionary?
To sum values for a single subkey you could use sum()
with a generator expression:
>>> d = {'A': {'val1': 3,'val2': 5}, 'B': {'val1': 2, 'val2': 6}}
>>> sum(x['val1'] for x in d.values())
5
To sum values for all subkeys you can use collections.Counter
:
>>> from collections import Counter
>>> counter = sum(map(Counter, d.values()), Counter())
>>> dict(counter)
{'val2': 11, 'val1': 5}
Sum the values of dictionaries inside a list where the keys are the same
IIUC this is pretty straight forward. You just write a function to sum up all values per key. Then apply it to the transposed list of lists of dicts.
def sum_by_key(dicts):
result = {}
for d in dicts:
for k, v in d.items():
result[k] = result.get(k, 0) + v
return result
lists_of_dicts = [[{1:2, 3:4}, {1:10, 2:9}], [{3:8, 2:4}, {3:1, 2:5}]]
result = [sum_by_key(dicts) for dicts in zip(*lists_of_dicts)]
print(result)
(lists_of_dicts
would be [A, B, C, D]
with your variables)
Output:
[{1: 2, 3: 12, 2: 4}, {1: 10, 2: 14, 3: 1}]
edit: with your new sample data
lists_of_dicts = [A, B, C, D]
result = [sum_by_key(dicts) for dicts in zip(*lists_of_dicts)]
print(result)
produces
[{'1': 1158, '2': 1450, '3': 542, '4': 2060}, {'1': 702, '2': 2600, '3': 1169, '4': 1670}, {'1': 880, '2': 2480, '3': 2000, '4': 3852}, {'1': 600, '2': 640, '3': 1142, '4': 6230}]
how can I sum values in a dictionary based on just one element of the tuple in the keys?
Use sum()
on dictionary values where first item of tuple is 'B'
(Edited as per @rafaelc): Cleaner to not use the ternary operator here
sum(val for key, val in dict.items() if key[0] == 'B')
Instead of original:
sum(val if key[0] == 'B' else 0 for key, val in dict.items())
Also, refrain from calling your dictionary as dict
How to sum values in dictionary based on position?
You can use the zip()
function
aa = {"A": [0, 0.12, 0, 0.73, 0], "B": [0.96, 0, 0.30, 0, 0], "C": [0, 0, 0, 0.11, 0], "D": [0, 0.07, 0, 0.42, 0]}
bb = []
for value in (zip(*list(aa.values()))):
bb.append(sum(value))
print (bb)
output :
[0.96, 0.19, 0.3, 1.26, 0]
Related Topics
How to Create a "View" on a Python List
How to Create Animated Sprites Using Sprite Sheets in Pygame
How to Read and Write Ini File with Python3
Absolute VS. Explicit Relative Import of Python Module
How to Color Python Logging Output
Retrieve List of Tasks in a Queue in Celery
Remove Trailing Newline from the Elements of a String List
How to Do/Workaround a Conditional Join in Python Pandas
How to Deal with Multi-Level Column Names Downloaded with Yfinance
Getting a Callback When a Tkinter Listbox Selection Is Changed
Separation of Business Logic and Data Access in Django
Python: Pandas Series - Why Use Loc
How to Change Values in a Tuple
Why Do I Get Typeerror: Can't Multiply Sequence by Non-Int of Type 'Float'
What Do the Python File Extensions, .Pyc .Pyd .Pyo Stand For
Python Assigning Multiple Variables to Same Value? List Behavior