0

I'm looking for a way to merge dictionaries by other means than dict(a.items()+b.items()) is doing.

Example:

foo = {'cart':
  {'item':
    {'1':
      {'amount':
        'X',
      },
    },
  },
}

bar = {'cart': 
  {'item':
    {'2': 
      {'amount': 
        'Y',
      },
    },
  },
}

Wanted result:

res = {'cart':
  {'item':
    {'1':
      {'amount':
        'X'
      },
    },
    {'2': 
      {'amount': 
        'Y',
      },
    },
  },
}

Actual result (gotten bei dict(foo.items() + bar.items()):

res = {'cart':
  {'item':
    {'2': 
      {'amount': 
        'Y',
      },
    },
  },
}

Thanks a lot in advance!

daten
  • 131
  • 1
  • 1
  • 12
  • what you have tried already ? – Mazdak Jan 26 '15 at 19:23
  • ...so you want to update the dictionary under `res['cart']`, and not `res` itself. Or do you have any other key besides `cart` you want to update? – Roberto Jan 26 '15 at 19:25
  • 1
    possible duplicate of [Dictionaries of dictionaries merge](http://stackoverflow.com/questions/7204805/dictionaries-of-dictionaries-merge) – Daniel Robinson Jan 26 '15 at 19:31
  • Best answer I've seen: http://stackoverflow.com/a/3233356/893113 – paulmelnikow Jan 27 '15 at 02:55
  • 1
    possible duplicate of [Update value of a nested dictionary of varying depth](http://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth) – paulmelnikow Jan 27 '15 at 02:55

1 Answers1

1

Found that code snippet which does fairly well for my usecase:

def deepupdate(original, update):
    """
    Recursively update a dict.
    Subdict's won't be overwritten but also updated.
    """
    for key, value in original.iteritems():
        if not key in update:
            update[key] = value
        elif isinstance(value, dict):
            deepupdate(value, update[key])
    return update
daten
  • 131
  • 1
  • 1
  • 12