Append Dictionary Python

karena format json dan dictionary dipython sangat mirip, saya menggunakan permisalan di json. kasusnya kita mempunyai file inventory seperti berikut :

{
    "host": {
        "Spine1": {
            "ipaddress": "192.168.1.1",
            "user": "vyos1",
            "password": "vyos1"
        },
        "Spine2": {
            "ipaddress": "192.168.2.1",
            "user": "vyos2",
            "password": "vyos2"
        }
    }
}

kita harus menambahkan sebuah data lagi (spine3 dan yang lain kedalam data tersebut, contohnya :

{
    'Spine4': {
        'password': 'vyos1',
        'ipaddress': '192.168.1.1',
        'user': 'vyos1'
    }
}

oke, mari kita buat programnya :

import ast

# open json and read into raw text
raw = open('inventory.json').read()

# loads the raw into loads() function to create dict string type
data = ast.literal_eval(raw)

# add data that will be append to main data
data2 = {'Spine4': {
    'password': 'vyos1',
    'ipaddress': '192.168.1.1',
    'user': 'vyos1'
}}

# append the data2 to data
data["host"].update(data2)

# check data
print (data)

jalankan program tersebut :

zufar@zufar:~/Documents/Technology/Programming/Python/mysql-dict$ python program.py
{'host': {'Spine1': {'password': 'vyos1', 'ipaddress': '192.168.1.1', 'user': 'vyos1'}, 'Spine2': {'password': 'vyos2', 'ipaddress': '192.168.2.1', 'user': 'vyos2'}, 'Spine4': {'password': 'vyos1', 'ipaddress': '192.168.1.1', 'user': 'vyos1'}}}

oke, bisa terlihat data tertambahkan. mari kita coba perbaiki agar mudah dibaca :

{
    'host': {
        'Spine1': {
            'password': 'vyos1',
            'ipaddress': '192.168.1.1',
            'user': 'vyos1'
        },
        'Spine2': {
            'password': 'vyos2',
            'ipaddress': '192.168.2.1',
            'user': 'vyos2'
        },
        'Spine4': {
            'password': 'vyos1',
            'ipaddress': '192.168.1.1',
            'user': 'vyos1'
        }
    }
}

 

 

Comments are closed.