简体   繁体   English

将新的键/值添加到 json 字典 python

[英]add new key/value to json dictionary python

I have the following json data:我有以下 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
}

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 .count的值大于groupid的可用插槽count时,我收到该错误。 So in other words, right now, groupid has 2 slots, which I can update easily.换句话说,现在groupid有 2 个插槽,我可以轻松更新。 But when I try to add a new key/value for groupid, I get the aforementioned error.但是,当我尝试为 groupid 添加新的键/值时,出现上述错误。

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?谁能发现我的代码有什么问题?

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

hostcreate['params']['groups'] is a list, so you need append to add new item to it: hostcreate['params']['groups']是一个列表,因此您需要append向其添加新项目:

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

update :更新

You didn't provide a MVCE so I can only guess what you want to do.您没有提供MVCE,所以我只能猜测您想做什么。 The code you added at the update part can indeed be rewritten to make it more pythonic:您在更新部分添加的代码确实可以重写以使其更加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.这将替换整个列表,我看到您在 while 循环之前将 count 初始化为 0 时正在尝试执行此操作。

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可能有一个更优雅的解决方法,但这只是将一个空字典附加到groups列表中,以便您可以向其中添加键:值

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python:无法向字典添加新的key:value - Python: Unable to add a new key:value to a dictionary 在Python字典中添加新的键值对 - Add new key value pair in a Python Dictionary Python [嵌套字典] - 如何添加新的键/值来创建这种字典结构:d = {key:{key:value, key:value, key:value}} - Python [Nested Dictionary] - How to add new key/values to create this structure of dictionary: d = {key:{key:value, key:value, key:value}} Python字典添加新键值对的简单方法 - Python dictionary simple way to add a new key value pair 向 Python 中的嵌套字典添加新键值的有效方法? - Efficient way to add a new key-value to a nested dictionary in Python? 如何将新键添加到现有字典并将前一个键作为值附加到 for 循环中创建的新键:python - How to add a new key to an existing dictionary and append previous key as value to the new key created in a for loop : python 在字典中转换2元组键并将其作为字典值添加到新字典中 - Convert 2-tuple key in dictionary and add to a new dictionary as a dictionary value 如何向字典添加新的键值 - How to add new key-value to dictionary 在现有字典中添加一个新键:值并使用 pickle 保存它,然后将该字典加载到另一个 python 文件中 - Add a new key : value inside a existing dictionary and save that using pickle and then load that dictionary in another python file Python:如何遍历词典列表并将每个词典作为值添加到具有唯一键的新词典中-无需重复 - Python: How to iterate over a list of dictionaries and add each dictionary as value to a new dictionary with a unique key - no repeats
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM