Passed
Push — master ( 60d050...2d519d )
by Fabio
01:05
created

benedict.dicts.benedict.get_list_item()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nop 5
1
# -*- coding: utf-8 -*-
2
3
from benedict.core import clean as _clean
4
from benedict.core import clone as _clone
5
from benedict.core import dump as _dump
6
from benedict.core import filter as _filter
7
from benedict.core import find as _find
8
from benedict.core import flatten as _flatten
9
from benedict.core import groupby as _groupby
10
from benedict.core import invert as _invert
11
from benedict.core import items_sorted_by_keys as _items_sorted_by_keys
12
from benedict.core import items_sorted_by_values as _items_sorted_by_values
13
from benedict.core import keypaths as _keypaths
14
from benedict.core import merge as _merge
15
from benedict.core import move as _move
16
from benedict.core import nest as _nest
17
from benedict.core import remove as _remove
18
from benedict.core import rename as _rename
19
from benedict.core import search as _search
20
from benedict.core import standardize as _standardize
21
from benedict.core import subset as _subset
22
from benedict.core import swap as _swap
23
from benedict.core import traverse as _traverse
24
from benedict.core import unflatten as _unflatten
25
from benedict.core import unique as _unique
26
from benedict.dicts.io import IODict
27
from benedict.dicts.keylist import KeylistDict
28
from benedict.dicts.keypath import KeypathDict
29
from benedict.dicts.parse import ParseDict
30
31
32
class benedict(KeypathDict, IODict, ParseDict):
33
34
    def __init__(self, *args, **kwargs):
35
        """
36
        Constructs a new instance.
37
        """
38
        if len(args) == 1 and isinstance(args[0], benedict):
39
            super(benedict, self).__init__(args[0].dict())
40
            return
41
        super(benedict, self).__init__(*args, **kwargs)
42
43
    def __getitem__(self, key):
44
        return self._cast(
45
            super(benedict, self).__getitem__(key))
46
47
    def _cast(self, value):
48
        """
49
        Cast a dict instance to a benedict instance
50
        keeping the pointer to the original dict.
51
        """
52
        if isinstance(value, dict) and not isinstance(value, benedict):
53
            return benedict(value, keypath_separator=self._keypath_separator)
54
        return value
55
56
    def clean(self, strings=True, collections=True):
57
        """
58
        Clean the current dict instance removing all empty values: None, '', {}, [], ().
59
        If strings or collections (dict, list, set, tuple) flags are False,
60
        related empty values will not be deleted.
61
        """
62
        _clean(self, strings=strings, collections=collections)
63
64
    def clone(self):
65
        """
66
        Creates and return a clone of the current dict instance (deep copy).
67
        """
68
        return self._cast(
69
            _clone(self))
70
71
    def copy(self):
72
        """
73
        Creates and return a copy of the current instance (shallow copy).
74
        """
75
        return self._cast(
76
            super(benedict, self).copy())
77
78
    def deepcopy(self):
79
        """
80
        Alias of 'clone' method.
81
        """
82
        return self.clone()
83
84
    def deepupdate(self, other, *args):
85
        """
86
        Alias of 'merge' method.
87
        """
88
        self.merge(other, *args)
89
90
    def dump(self, data=None):
91
        """
92
        Return a readable string representation of any dict/list.
93
        This method can be used both as static method or instance method.
94
        """
95
        return _dump(data or self)
96
97
    def filter(self, predicate):
98
        """
99
        Return a new filtered dict using the given predicate function.
100
        Predicate function receives key, value arguments and should return a bool value.
101
        """
102
        return _filter(self, predicate)
103
104
    def find(self, keys, default=None):
105
        """
106
        Return the first match searching for the given keys.
107
        If no result found, default value is returned.
108
        """
109
        return _find(self, keys, default)
110
111
    def flatten(self, separator='_'):
112
        """
113
        Return a new flattened dict using the given separator
114
        to join nested dict keys to flatten keypaths.
115
        """
116
        return _flatten(self, separator)
117
118
    def get(self, key, default=None):
119
        return self._cast(
120
            super(benedict, self).get(key, default))
121
122
    def get_dict(self, key, default=None):
123
        return self._cast(
124
            super(benedict, self).get_dict(key, default))
125
126
    def get_list_item(self, key, index=0, default=None, separator=','):
127
        return self._cast(
128
            super(benedict, self).get_list_item(key, index, default, separator))
129
130
    def groupby(self, key, by_key):
131
        """
132
        Group a list of dicts at key by the value of the given by_key and return a new dict.
133
        """
134
        return self._cast(
135
            _groupby(self[key], by_key))
136
137
    def invert(self, flat=False):
138
        """
139
        Return a new inverted dict, where values become keys and keys become values.
140
        Since multiple keys could have the same value, each value will be a list of keys.
141
        If flat is True each value will be a single value (use this only if values are unique).
142
        """
143
        return _invert(self, flat)
144
145
    def items_sorted_by_keys(self, reverse=False):
146
        """
147
        Return items (key/value list) sorted by keys.
148
        If reverse is True, the list will be reversed.
149
        """
150
        return _items_sorted_by_keys(self, reverse=reverse)
151
152
    def items_sorted_by_values(self, reverse=False):
153
        """
154
        Return items (key/value list) sorted by values.
155
        If reverse is True, the list will be reversed.
156
        """
157
        return _items_sorted_by_values(self, reverse=reverse)
158
159
    def keypaths(self):
160
        """
161
        Return a list of all keypaths in the dict.
162
        """
163
        sep = self._keypath_separator or '.'
164
        return _keypaths(self, separator=sep)
165
166
    def merge(self, other, *args, **kwargs):
167
        """
168
        Merge one or more dict objects into current instance (deepupdate).
169
        Sub-dictionaries will be merged toghether.
170
        If overwrite is False, existing values will not be overwritten.
171
        """
172
        _merge(self, other, *args, **kwargs)
173
174
    def move(self, key_src, key_dest):
175
        """
176
        Move a dict instance value item from 'key_src' to 'key_dst'.
177
        If key_dst exists, its value will be overwritten.
178
        """
179
        _move(self, key_src, key_dest)
180
181
    def nest(self, key, id_key='id', parent_id_key='parent_id', children_key='children'):
182
        """
183
        Nest a list of dicts at the given key and return a new nested list
184
        using the specified keys to establish the correct items hierarchy.
185
        """
186
        return _nest(self[key], id_key, parent_id_key, children_key)
187
188
    def pop(self, key, *args):
189
        return self._cast(
190
            super(benedict, self).pop(key, *args))
191
192
    def remove(self, keys, *args):
193
        """
194
        Remove multiple keys from the current dict instance.
195
        It is possible to pass a single key or more keys (as list or *args).
196
        """
197
        _remove(self, keys, *args)
198
199
    def setdefault(self, key, default=None):
200
        return self._cast(
201
            super(benedict, self).setdefault(key, default))
202
203
    def rename(self, key, key_new):
204
        """
205
        Rename a dict item key from 'key' to 'key_new'.
206
        If key_new exists, a KeyError will be raised.
207
        """
208
        _rename(self, key, key_new)
209
210
    def search(self, query,
211
               in_keys=True, in_values=True,
212
               exact=False, case_sensitive=False):
213
        """
214
        Search and return a list of items (dict, key, value, ) matching the given query.
215
        """
216
        return _search(self, query, in_keys, in_values, exact, case_sensitive)
217
218
    def standardize(self):
219
        """
220
        Standardize all dict keys (e.g. 'Location Latitude' -> 'location_latitude').
221
        """
222
        _standardize(self)
223
224
    def subset(self, keys, *args):
225
        """
226
        Return a new dict subset for the given keys.
227
        It is possible to pass a single key or multiple keys (as list or *args).
228
        """
229
        return _subset(self, keys, *args)
230
231
    def swap(self, key1, key2):
232
        """
233
        Swap items values at the given keys.
234
        """
235
        _swap(self, key1, key2)
236
237
    def traverse(self, callback):
238
        """
239
        Traverse the current dict instance (including nested dicts),
240
        and pass each item (dict, key, value) to the callback function.
241
        """
242
        _traverse(self, callback)
243
244
    def unflatten(self, separator='_'):
245
        """
246
        Return a new unflattened dict using the given separator
247
        to split dict keys to nested keypaths.
248
        """
249
        return _unflatten(self, separator)
250
251
    def unique(self):
252
        """
253
        Remove duplicated values from the current dict instance.
254
        """
255
        _unique(self)
256