-
Notifications
You must be signed in to change notification settings - Fork 3
/
mdict.py
53 lines (50 loc) · 1.41 KB
/
mdict.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def mget(m_dict, keys, default=None, delimiter=':'):
"""
:param m_dict: A dictionary to search inside of
:type m_dict: dict
:param keys: A list of keys
:type keys: str
:param default: A default value to return if none found
:param delimiter: The delimiter used in the keys list
:type delimiter: str
:return: The value according to the keys list
"""
val = m_dict
keys = keys.split(delimiter)
for key in keys:
try:
val = val[key]
except KeyError:
return default
except TypeError:
return default
return val
def mset(m_dict, keys, value, delimiter=':'):
"""
:param m_dict: A dictionary to set the value inside of
:type m_dict: dict
:param keys: A list of keys
:type keys: str
:param value: The value to set inside of the dictionary
:param delimiter: The delimiter used in the keys list
:type delimiter: str
"""
val = m_dict
keys = keys.split(delimiter)
for i, key in enumerate(keys):
try:
if i == len(keys) - 1:
val[key] = value
return
else:
val = val[key]
except KeyError:
if i == len(keys) - 1:
val[key] = value
return
else:
val[key] = {}
val = val[key]
class MDict(dict):
get = mget
set = mset