| Total Complexity | 5 |
| Total Lines | 38 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | def flatten(dictionary): |
||
| 2 | result = {} |
||
| 3 | for key, value in dictionary.items(): |
||
| 4 | if isinstance(value, dict): |
||
| 5 | if value: |
||
| 6 | ret = flatten(value) |
||
| 7 | for i in ret: |
||
| 8 | result[key + '/' + i] = ret[i] |
||
| 9 | else: |
||
| 10 | result[key] = '' |
||
| 11 | else: |
||
| 12 | result[key] = value |
||
| 13 | return result |
||
| 14 | |||
| 15 | |||
| 16 | if __name__ == '__main__': # pragma: no cover |
||
| 17 | # These "asserts" using only for self-checking and not necessary for |
||
| 18 | # auto-testing |
||
| 19 | assert flatten({"key": "value"}) == {"key": "value"}, "Simple" |
||
| 20 | assert flatten({"key": {"deeper": {"more": {"enough": "value"}}}}) == { |
||
| 21 | "key/deeper/more/enough": "value" |
||
| 22 | }, "Nested" |
||
| 23 | assert flatten({"empty": {}}) == {"empty": ""}, "Empty value" |
||
| 24 | assert flatten( |
||
| 25 | { |
||
| 26 | "name": {"first": "One", "last": "Drone"}, |
||
| 27 | "job": "scout", |
||
| 28 | "recent": {}, |
||
| 29 | "additional": {"place": {"zone": "1", "cell": "2"}}, |
||
| 30 | } |
||
| 31 | ) == { |
||
| 32 | "name/first": "One", |
||
| 33 | "name/last": "Drone", |
||
| 34 | "job": "scout", |
||
| 35 | "recent": "", |
||
| 36 | "additional/place/zone": "1", |
||
| 37 | "additional/place/cell": "2", |
||
| 38 | } |
||
| 39 |