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



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

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

所有的键和值都是我从其他模块获得的变量。 我创建了一个空字典call_record=[{}]要添加"source1"、"source2"作为我尝试的键,

call_record.append({source1 :})

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

此外,要添加"目的地11","目的地12"ets,我尝试过,

call_record[i].append(destination11) 

但是,这不会将目标添加为源键的值。

添加

目的地后,我必须添加日期时间。然后我必须将此字典转储到 json 文件中。

.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中的数据结构

您还可以参考文档的 JSON 编码器和解码器部分,以获取有关如何使用它的更多示例。

最新更新