0

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)
Community
  • 1
  • 1
Moritz
  • 5,130
  • 10
  • 40
  • 81
  • I'm having a hard time understanding what you're asking for. Can you provide an example of code that fails to do what you want? – Daniel Pryden Apr 30 '15 at 22:28
  • 1
    if key is in dict add new values else create new k/v pairing, don't simply update, check for the keys first. Using update is always going to overwrite – Padraic Cunningham Apr 30 '15 at 22:31
  • 1
    @PadraicCunningham to add to that: if you had a "deep update" method in place of just update, then code with this structure would make sense. But you'd have to write that deep update yourself. And it may be simpler just to restructure the code the way Padraic implies. – abarnert Apr 30 '15 at 22:39
  • @Padraic so you would check within each loop if the current key exists ? – Moritz Apr 30 '15 at 22:56
  • @Moritz, yes, that or use a defaultdict but the order won't be maintained – Padraic Cunningham Apr 30 '15 at 23:30

0 Answers0