KLZY
KLZY

Reputation: 83

add new key/value to json dictionary python

I have the following json data:

hostcreate = {
    "jsonrpc": "2.0",
    "method": "host.create",
    "params": {
        "host": "my_host",
        "port": 10050,
        "interfaces": [{
            "type": 1,
            "main": 1,
            "useip": 1,
            "ip": "10.100.200.200",
            "dns": "",
            "port": "10050"
        }],
        "groups": [{
            "groupid": 2
        }, {
            "groupid": 22
        }]
    },
    "auth": "byese31blahblah",
    "id": 1
}

I can update the values of existing keys with something like this:

hostcreate['params']['port'] = str(newhostport)

However, when I try to add a new key/value to the dictionary, I get an error:

    hostcreate['params']['groups'][count]['groupid'] = int(eachgroupid)
IndexError: list index out of range

I'm getting that error when the value of count is greater than the number of available slots for groupid. So in other words, right now, groupid has 2 slots, which I can update easily. But when I try to add a new key/value for groupid, I get the aforementioned error.

How can I resolve this?

UPDATE:

Here's the code (which isn't working):

    numofgroups = len(groupids.split(","))
    rnumofgroups = numofgroups - 1
    count = 0
    existinggids = len(hostcreate['params']['groups']) - 1
    while (count <= numofgroups):
        eachgroupid = groupids.split(",")[count]
        if count <= existinggids:
            count = count + 1
            hostcreate['params']['groups'][count]['groupid'] = int(eachgroupid)
        else:
            count = count + 1
            hostcreate['params'['groups'].append({
                'groupid':int(eachgroupid)
            })

every time I run this, it keeps complaining. can anyone spot what is wrong with my code?

Upvotes: 1

Views: 365

Answers (3)

adrtam
adrtam

Reputation: 7241

hostcreate['params']['groups'] is a list, so you need append to add new item to it:

hostcreate['params']['groups'].append({
    'groupid':  int(eachgroupid)
})

update:

You didn't provide a MVCE so I can only guess what you want to do. The code you added at the update part can indeed be rewritten to make it more pythonic:

hostceate["params"]["groups"] = [{"groupid": int(g)} for g in groupids.split(",")]

This replace the whole list, which I see you're trying to do as you initialized count to 0 before the while loop.

Upvotes: 0

SuperStew
SuperStew

Reputation: 3064

i would do something like

try:
    hostcreate['params']['groups'][count]['groupid'] = int(eachgroupid)

except:
    hostcreate['params']['groups'].append({})
    hostcreate['params']['groups'][count]['groupid'] = int(eachgroupid)

theres probably a more elegant work around, but this just appends an empty dict to the groups list so you can add the key:value to it

Upvotes: 0

Alexandru Martin
Alexandru Martin

Reputation: 236

You have to append to the list hostcreate['params'['groups'].append({'groupid':int(eachgroupid)})

Upvotes: 1

Related Questions