可以通过以下方式实现:
def convert_dict_to_nested_list(dictionary, keyword):
nested_list = []
for key, value in dictionary.items():
if isinstance(value, dict):
nested_list.append([key, convert_dict_to_nested_list(value, keyword)])
else:
nested_list.append([key, value])
nested_list.append([keyword])
return nested_list
这个函数接受两个参数,第一个参数是要转换的字典(dictionary),第二个参数是要插入的关键字(keyword)。函数首先创建一个空的嵌套列表(nested_list),然后遍历字典的键值对。如果值是一个字典,则递归调用函数将其转换为嵌套列表,并将结果作为子列表插入到nested_list中。如果值不是字典,则直接将键值对作为子列表插入到nested_list中。最后,在每个子列表的末尾插入关键字。
以下是一个示例:
my_dict = {
"key1": "value1",
"key2": {
"subkey1": "subvalue1",
"subkey2": "subvalue2"
},
"key3": "value3"
}
nested_list = convert_dict_to_nested_list(my_dict, "keyword")
print(nested_list)
输出结果为:
[['key1', 'value1'], ['key2', [['subkey1', 'subvalue1'], ['subkey2', 'subvalue2'], ['keyword']]], ['key3', 'value3'], ['keyword']]
在这个示例中,字典my_dict被转换为嵌套列表nested_list,并在每个子列表中插入了关键字"keyword"。
领取专属 10元无门槛券
手把手带您无忧上云