I do generate data within a loop and I can converted the data to a dictionary using the answer from Alex Martelli from this SO thread :
import collections
def update(d, u):
for k, v in u.iteritems():
if isinstance(v, collections.Mapping):
r = update(d.get(k, {}), v)
d[k] = r
else:
d[k] = u[k]
return d
This Solution works fine as long as the values are stored in a list and the last key does not occur more that one:
The function can be used to construct nested dictionaries:
import numpy as np
from collections import OrderedDict
dummy_data = np.arange(5,7,1)
pH = np.arange(4,5,1)
salt = np.arange(10,11,1)
names = ['k','l','m']
my_dict = OrderedDict()
a = []
b = []
for i in pH:
for ii in salt:
for iii in dummy_data:
result_1 = 1*iii
result_2 = 10*iii
a.append(result_1)
b.append(result_2)
u = {i:{ii:{'a':a, 'b': b}}}
update_dict(my_dict,u)
This method works fine as long as update_dict
is not called within the last loop. The output is:
OrderedDict([(4, {11: {'a': [5, 6], 'b': [50, 60]}})])
Is there a way to add datapoints to a dictionary without the danger of deleting entries ? At the same time if new keys appear, they should be added.
What does not work:
for i in pH:
for ii in salt:
for iii in dummy_data:
result_1 = 1*iii
result_2 = 10*iii
u = {i:{ii:{'a':result_1, 'b': result_2}}}
update_dict(my_dict,u)