使用python将元素附加到json字典中的标记

2024-06-02 07:04:37 发布

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

如何将特定值附加到json文件字典的特定标记中

{"dict": [
    {
     "tag": "adult",
     "name": ["John", "Elle"],
     "age": ["25", "23"],
    },
    {
     "tag": "elderly",
     "name": ["Mary", "Matthew"],
     "age": ["67", "80"],
}

在这里,用户输入姓名和年龄后,要想找到一种方法,在特定的标记中附加到json文件中(例如,年龄29岁的名为“Stacy”的人只应添加到“成人”中

因此,如果我们在成人标签中添加例如“29岁的Stacy”,则更新后的标签应该是这样的:

{
     "tag": "adult",
     "name": ["John", "Elle", "Stacy"],
     "age": ["25", "23", "29"],
}

Tags: 文件name标记jsonage字典tag标签
2条回答

为此,必须遍历存储在给定json字典中的字典列表。 如果我假设您已将json加载到名为'elements_dict'的变量中,那么您必须迭代元素[u dict['dict']以访问该元素并执行必要的操作。 由于您没有提到将某人划分为成年人的年龄标准,我假设任何50岁以下的人都可以被视为成年人:)并提出了以下方法(对您来说,这只是一个非常简单的表示,您可以相应地改进)

elements_dict = {"dict": [
    {
     "tag": "adult",
     "name": ["John", "Elle"],
     "age": ["25", "23"],
    },
    {
     "tag": "elderly",
     "name": ["Mary", "Matthew"],
     "age": ["67", "80"],
    }]
}

new_name = "Stacy"
new_age = "29"

for people in elements_dict['dict']:
    if people['tag'] == 'adult' and int(new_age) < 50:
        people['name'].append(new_name)
        people['age'].append(new_age)
    elif people['tag'] == 'elderly' and int(new_age) >= 50:
        people['name'].append(new_name)
        people['age'].append(new_age)

print(elements_dict)

是否有理由将整个字典值放入列表而不是保留在字典中。如果不是,我建议如下:

dict = { "adult": { "name": ["John", "Elle"], "age": ["25", "23"] },  "elderly": { "name": ["Mary", "Matthew"], "age": ["67", "80"] }}

现在,“成人”和“老年人”是字典的关键,您可以这样访问它们:

dict["adult"] = { "name": ["John", "Elle"], "age": ["25", "23"] }
dict["elderly"] = { "name": ["Mary", "Matthew"], "age": ["67", "80"]}

并附加如下示例情况:

dict["adult"]["name"].append("Stacy")
dict["adult"]["age"].append("29")

这将导致整个dict输出:

dict = { "adult": { "name": ["John", "Elle","Stacy"], "age": ["25", "23","29"] },  "elderly": { "name": ["Mary", "Matthew"], "age": ["67", "80"] }}

相关问题 更多 >