向json字典python添加新的键/值

2024-04-25 05:17:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下json数据:

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
}

我可以用以下方法更新现有键的值:

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

但是,当我尝试向字典中添加新的键/值时,出现了一个错误:

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

count的值大于groupid的可用插槽数时,我得到了这个错误。换句话说,现在,groupid有2个插槽,我可以很容易地更新。但是当我尝试为groupid添加一个新的键/值时,我得到了前面提到的错误。你知道吗

我如何解决这个问题?你知道吗

更新:

下面是代码(不起作用):

    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)
            })

每次我运行这个,它总是抱怨。有人能发现我的代码有什么问题吗?你知道吗


Tags: 代码hostlenportcount错误paramsint
3条回答

hostcreate['params']['groups']是一个列表,因此需要append向其中添加新项:

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

更新

你没有提供MVCE,所以我只能猜测你想做什么。您在更新部分添加的代码确实可以重写以使其更具python风格:

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

这将替换整个列表,我看到您在while循环之前尝试将count初始化为0。你知道吗

您必须附加到列表hostcreate['params'['groups'].append({'groupid':int(eachgroupid)})

我会做一些像

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

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

可能有一个更优雅的解决方法,但这只是将一个空的dict附加到groups列表中,这样您就可以添加关键字:值到它

相关问题 更多 >