[英]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.