Completed
Push — master ( 18d750...3bad9e )
by Andrii
11:56
created

heppy.merge_dict()   A

Complexity

Conditions 4

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 4
dl 0
loc 13
rs 9.2
1
import json
2
import collections
3
4
from pprint import pprint
5
6
# http://stackoverflow.com/questions/10703858
7
def merge_dict(d1, d2):
8
    """
9
    Modifies d1 in-place to contain values from d2.  If any value
10
    in d1 is a dictionary (or dict-like), *and* the corresponding
11
    value in d2 is also a dictionary, then merge them in-place.
12
    """
13
    for k,v2 in d2.items():
14
        v1 = d1.get(k) # returns None if v1 has no value for this key
15
        if (isinstance(v1, collections.Mapping)
16
        and isinstance(v2, collections.Mapping)):
17
            merge_dict(v1, v2)
18
        else:
19
            d1[k] = v2
20
21
class Config(dict):
22
    def __init__(self, path):
23
        with open(path) as file:
24
            self.merge(json.load(file))
25
26
    def merge(self, data):
27
        merge_dict(self, data)
28
29