在python中添加具有空值的键,然后以嵌套格式添加值

2024-05-29 02:36:07 发布

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

我正在尝试以以下格式创建并添加元素到字典中

{{"source1": { "destination11": ["datetime1", "datetime2", ....]}
            { "destination12": ["datetime3", "datetime4",....]}
            ........................................
}
{"source2": { "destination21": ["datetime5", "datetime6", ....]}
            { "destination22": ["datetime7", "datetime8",....]}
            .......................................
}
.........................................}

所有的键和值都是我从其他模块得到的变量。 我创造了一本空字典 呼叫记录=[{}] 要添加“source1”、“source2”作为我尝试的键

^{pr2}$

现在我还不能为这个键添加值,因为我将在下一行中添加它,所以我需要用空值创建这个键,然后在下一个模块中获取值时添加值。但是,这一行没有创建值为空的键。在

另外,为了增加“目的地11”,“目的地12”等,我尝试了

call_record[i].append(destination11) 

但是,这并没有将目的地添加为源键的值。在

我必须在添加目的地之后添加日期时间。然后我必须将这个字典转储到一个json文件中。在


Tags: 模块元素字典格式目的地datetime2source1source2
1条回答
网友
1楼 · 发布于 2024-05-29 02:36:07

.append用于向数组中添加元素。 向字典中添加元素的正确sintax是your_dictionary[key] = value

在您的情况下,您可以将参数传递到字典,如下所示:

import json

call_record = {} # To create an empty dictionary
call_record["source1"] = {} # To append an empty dictionary to the key "source1"
call_record["source1"]["destination11"] = [] # An empty array as value for "destination11"
call_record["source1"]["destination11"].append("datetime1", "datetime2") # To append element datetime1 and datetime2 to destination11 array
call_record_json = json.dumps(call_record, ensure_ascii=False)

不过,我建议您看一下python文档,以澄清python中的data structure。在

您还可以参考文档的JSON encoder and decoder一节,了解如何使用它的更多示例。在

相关问题 更多 >

    热门问题