我想将新关键字添加到字典列表中。示例:
"label" : []
(带有空白列表)
[
{
"Next" : {
"seed" : [
{
"Argument" : [
{
"id" : 4,
"label" : "org"
},
{
"id" : "I"
},
{
"word" : "He",
"seed" : 2,
"id" : 3,
"label" : "object"
},
{
"word" : "Gets",
"seed" : 9,
"id" : 2,
"label" : "verb"
}
]
}
],
"Next" : "he,get",
"time" : ""
}
}
]
我试图在“种子”中使用循环,然后在“参数”中使用循环,然后在循环中使用.update(“ label”:[]),但它不起作用。谁能给我一个使用for循环从头开始然后添加这些新“标签”的示例吗?
我的首选目标:(根据我的输入在字典中添加额外的“标签”)
示例:
[
{
"Next" : {
"seed" : [
{
"Argument" : [
{
"id" : 4,
"label" : "org"
},
{
"id" : "I"
},
{
"word" : "He",
"seed" : 2,
"id" : 3,
"label" : "object"
},
{
"word" : "Gets",
"seed" : 9,
"id" : 2,
"label" : "verb"
},
{
"id" : 5,
"label" : "EXTRA"
},
{
"id" : 6,
"label" : "EXTRA"
},
{
"id" : 7,
"label" : "EXTRA"
}
]
}
],
"Next" : "he,get",
"time" : ""
}
}
]
我是词典的新手,所以真的需要帮助
答案 0 :(得分:0)
您有一个包含一个嵌套字典的列表。获取内部字典的列表,然后进行迭代。假设您的初始数据结构名为 data
dict_list = data[0]['Next']['seed'][0]['Argument']
for item in dict_list:
item['label'] = input()
答案 1 :(得分:0)
首先,要访问需要更新的字典列表。
根据您指定的l[0]["Next"]["seed"][0]["Argument"]
然后迭代该列表,并检查label
是否已经存在,如果不存在,则将其添加为空列表。
这可以通过显式检查来完成:
if "label" not in i:
i["label"] = []
或通过重新分配:
i["label"] = i.get("label", [])
完整代码:
import pprint
l = [ {
"Next" : {
"seed" : [ {
"Argument" : [ {
"id" : 4,
"label" : "org"
}, {
"id" : "I"
}, {
"word" : "He",
"seed" : 2,
"id" : 3,
"label" : "object"
}, {
"word" : "Gets",
"seed" : 9,
"id" : 2,
"label" : "verb"
} ]
} ],
"Next" : "he,get",
"time" : ""
} }]
# access the list of dict that needs to be updated
l2 = l[0]["Next"]["seed"][0]["Argument"]
for i in l2:
i["label"] = i.get("label", []) # use the existing label or add an empty list
pprint.pprint(l)
输出:
[{'Next': {'Next': 'he,get',
'seed': [{'Argument': [{'id': 4, 'label': 'org'},
{'id': 'I', 'label': []},
{'id': 3,
'label': 'object',
'seed': 2,
'word': 'He'},
{'id': 2,
'label': 'verb',
'seed': 9,
'word': 'Gets'}]}],
'time': ''}}]
答案 2 :(得分:0)
如果我正确理解了您的问题,则要在没有dict
的{{1}}中的Argument
上添加'label'。您可以这样做-
label
for i in x[0]['Next']['seed'][0]['Argument']:
if not 'label' in i.keys():
i['label'] = []
是您的字典。但是x
是什么?
让我们简化您的字典-
x[0]['Next']['seed'][0]['Argument']:
我们如何到达这里? 让我们来看看-
x = [{'Next': {'Next': 'he,get',
'seed': [{'Argument': [{these}, {are}, {your}, {dicts}]}],
'time': ''}}]
我希望这是有道理的。并在x = [{'Next'(parent dict): {'Next'(child of previous 'Next'):{},
'seed(child of previous 'Next')':[{these}, {are}, {your}, {dicts}](a list of dicts)}]
Argument
现在您的# create a function that returns a dict
import random # I don't know how you want ids, so this
def create_dicts():
return {"id": random.randint(1, 10), "label": ""}
for i in range(3): # 3 is how many dicts you want to push in Argument
x[0]['Next']['seed'][0]['Argument'].append(create_dicts())
将变为-
dict