Commit 1cfffc69 authored by BorjaEst's avatar BorjaEst
Browse files

Add merge dict and white tests

parent 8b5958f3
import unittest
from o3skim import utils
dict_1 = {'a': 1, 'c': 0, 'z': {'a': 1, 'c': 0}}
dict_2 = {'b': 2, 'c': 3, 'z': {'b': 2, 'c': 3}}
class Tests_mergedict(unittest.TestCase):
def test_merge_d1d2(self):
dict_3 = dict_1.copy()
utils.mergedicts(dict_3, dict_2)
self.assertEqual(dict_2, {'b': 2, 'c': 3, 'z': {'b': 2, 'c': 3}})
self.assertEqual(dict_3['a'], 1)
self.assertEqual(dict_3['b'], 2)
self.assertEqual(dict_3['c'], 3)
self.assertEqual(dict_3['z'], {'a': 1, 'b': 2, 'c': 3})
def test_merge_d2d1(self):
dict_3 = dict_2.copy()
utils.mergedicts(dict_3, dict_1)
self.assertEqual(dict_1, {'a': 1, 'c': 0, 'z': {'a': 1, 'c': 0}})
self.assertEqual(dict_3['a'], 1)
self.assertEqual(dict_3['b'], 2)
self.assertEqual(dict_3['c'], 0)
self.assertEqual(dict_3['z'], {'a': 1, 'b': 2, 'c': 0})
...@@ -88,3 +88,20 @@ def save(file_name, metadata): ...@@ -88,3 +88,20 @@ def save(file_name, metadata):
""" """
with open(file_name, 'w+') as ymlfile: with open(file_name, 'w+') as ymlfile:
yaml.dump(metadata, ymlfile, allow_unicode=True) yaml.dump(metadata, ymlfile, allow_unicode=True)
def mergedicts(d1, d2):
"""Merges dict d2 in dict d2 recursively. If two keys exist in
both dicts, the value in d1 is superseded by the value in d2.
:param d1: Dict to be recursively completed by d2.
:type d1: dict
:param d2: Dict to be recursively merged in d1.
:type d2: dict
"""
for key in d2:
if key in d1 and isinstance(d1[key], dict) and isinstance(d2[key], dict):
mergedicts(d1[key], d2[key])
else:
d1[key] = d2[key]
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment