Reputation: 144
I am monitoring a device that is continuously updating a dictionary that I would like to add the current and next update of each values in place (eventually to do averaging on the data). The problem is I end up appending to the same dictionary. I am having trouble trying to keep the current dictionary and the next dictionary in the same loop without making it complicated...
data = {}
iteration 0:
data = { 'foo': [1,2,3], 'bar': [2,4,6]}
iteration 1:
data = { 'foo': [4,3,7], 'bar': [5,1,3]}
then sum both
datas = { 'foo': [5,5,10], 'bar':[7,5,9]}
and so on...
from collections import Counter
import random
import time
c = Counter()
def update_dict(data):
c.update(data) #I want to take the current values and then add it to the next iteration of these values
print dict(c)
while True:
blah = {i: random.random() for i in range(5)}
time.sleep(1)
update_dict(blah)
I supposed I can append the updating dictionary to a list of dictionaries and add them all at some point and then clear the list...
Upvotes: 0
Views: 104
Reputation: 1639
Something like this would collect the sums as in your example:
from itertools import zip_longest
data = {}
def update(new_data):
for key in new_data:
if key in data:
z = zip_longest(data[key], new_data[key], fillvalue = 0)
data[key] = [sum(i) for i in z]
else:
data[key] = new_data[key]
update({'foo': [1,2,3], 'bar': [2,4,6]})
update({'foo': [4,3,7], 'bar': [5,1,3]})
print(data)
Upvotes: 2
Reputation: 527
First, check to see if the key exists. If the key exists, then newList = [sum (a,b) for a,b in zip (data ('foo'),other_foo)]
Then update. Sorry for sloppy answer. Will fix later if necessary.
Upvotes: 1