File: basics.py

package info (click to toggle)
dotty-dict 1.3.1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 352 kB
  • sloc: python: 1,166; makefile: 192; sh: 5
file content (83 lines) | stat: -rw-r--r-- 2,437 bytes parent folder | download
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/env python
# -*- coding: utf-8 -*-

__author__ = 'Pawel Zadrozny'
__copyright__ = 'Copyright (c) 2018, Pawel Zadrozny'


def wrap_existing_dict():
    from dotty_dict import dotty

    data = {'status': 'ok', 'code': 200, 'data': {'timestamp': 1525018224,
                                                  'payload': []}}
    data = dotty(data)
    assert data['data.timestamp'] == 1525018224
    # end of wrap_existing_dict


def create_new_dotty():
    from dotty_dict import dotty

    data = dotty()
    data['status'] = 'ok'
    data['data.timestamp'] = 1525018224
    data['data.fancy.deeply.nested.key.for'] = 'fun'

    assert data == {'status': 'ok',
                    'data': {
                        'timestamp': 1525018224,
                        'fancy': {
                            'deeply': {
                                'nested': {
                                    'key': {
                                        'for': 'fun',
                                    },
                                },
                            },
                        },
                    }}
    # end of create_new_dotty


def builtin_methods():
    from dotty_dict import dotty

    dot = dotty({'status': 'ok',
                 'data': {
                     'timestamp': 1525018224,
                     'fancy': {
                         'deeply': {
                             'nested': {
                                 'key': {
                                     'for': 'fun',
                                 },
                             },
                         },
                     },
                 }})

    # get value, return None if not exist
    assert dot.get('data.payload') is None

    # pop key
    assert dot.pop('data.fancy.deeply.nested.key') == {'for': 'fun'}

    # get value and set new value if not exist
    assert dot.setdefault('data.payload', []) == []
    assert 'payload' in dot['data']

    # check what changed
    assert dot == {'status': 'ok',
                   'data': {
                       'timestamp': 1525018224,
                       'fancy': {
                           'deeply': {
                               'nested': {},
                           },
                       },
                       'payload': [],
                   }}

    # get keys
    assert sorted(dot.keys()) == ['data', 'status']
    # end of builtin_methods