1
|
|
|
# -*- coding: utf-8 -*- |
2
|
|
|
|
3
|
|
|
from six import string_types |
4
|
|
|
|
5
|
|
|
import copy |
6
|
|
|
import json |
7
|
|
|
|
8
|
|
|
|
9
|
|
|
def clean(d, strings=True, dicts=True, lists=True): |
10
|
|
|
keys = list(d.keys()) |
11
|
|
|
for key in keys: |
12
|
|
|
value = d.get(key, None) |
13
|
|
|
if not value: |
14
|
|
|
if value is None or \ |
15
|
|
|
strings and isinstance(value, string_types) or \ |
16
|
|
|
dicts and isinstance(value, dict) or \ |
17
|
|
|
lists and isinstance(value, (list, tuple, )): |
18
|
|
|
del d[key] |
19
|
|
|
|
20
|
|
|
|
21
|
|
|
def clone(d): |
22
|
|
|
return copy.deepcopy(d) |
23
|
|
|
|
24
|
|
|
|
25
|
|
|
def dump(data): |
26
|
|
|
def encoder(obj): |
27
|
|
|
json_types = (bool, dict, float, int, list, tuple, ) + string_types |
28
|
|
|
if not isinstance(obj, json_types): |
29
|
|
|
return str(obj) |
30
|
|
|
return json.dumps(data, indent=4, sort_keys=True, default=encoder) |
31
|
|
|
|
32
|
|
|
|
33
|
|
|
def flatten(d, separator='_', base=''): |
34
|
|
|
new_dict = {} |
35
|
|
|
keys = sorted(d.keys()) |
36
|
|
|
for key in keys: |
37
|
|
|
value = d.get(key) |
38
|
|
|
keypath = '{}{}{}'.format(base, separator, key) if base and separator else key |
39
|
|
|
if isinstance(value, dict): |
40
|
|
|
new_dict.update(flatten(value, separator, keypath)) |
41
|
|
|
else: |
42
|
|
|
new_dict[keypath] = value |
43
|
|
|
return new_dict |
44
|
|
|
|
45
|
|
|
|
46
|
|
|
def filter(d, predicate): |
47
|
|
|
if not callable(predicate): |
48
|
|
|
raise ValueError('predicate argument must be a callable.') |
49
|
|
|
new_dict = {} |
50
|
|
|
keys = d.keys() |
51
|
|
|
for key in keys: |
52
|
|
|
value = d.get(key, None) |
53
|
|
|
if predicate(key, value): |
54
|
|
|
new_dict[key] = value |
55
|
|
|
return new_dict |
56
|
|
|
|
57
|
|
|
|
58
|
|
|
def invert(d, flat=False): |
59
|
|
|
if flat: |
60
|
|
|
new_dict = { value:key for key, value in d.items() } |
61
|
|
|
else: |
62
|
|
|
new_dict = {} |
63
|
|
|
for key, value in d.items(): |
64
|
|
|
new_dict.setdefault(value, []).append(key) |
65
|
|
|
return new_dict |
66
|
|
|
|
67
|
|
|
|
68
|
|
|
def items_sorted_by_keys(d, reverse=False): |
69
|
|
|
return sorted(d.items(), key=lambda item: item[0], reverse=reverse) |
70
|
|
|
|
71
|
|
|
|
72
|
|
|
def items_sorted_by_values(d, reverse=False): |
73
|
|
|
return sorted(d.items(), key=lambda item: item[1], reverse=reverse) |
74
|
|
|
|
75
|
|
|
|
76
|
|
|
def merge(d, other): |
77
|
|
|
for key, value in other.copy().items(): |
78
|
|
|
src = d.get(key, None) |
79
|
|
|
if isinstance(src, dict) and isinstance(value, dict): |
80
|
|
|
merge(src, value) |
81
|
|
|
else: |
82
|
|
|
d[key] = value |
83
|
|
|
return d |
84
|
|
|
|