首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

将dict转换为嵌套列表,在每个子列表中插入关键字

可以通过以下方式实现:

代码语言:txt
复制
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中。最后,在每个子列表的末尾插入关键字。

以下是一个示例:

代码语言:txt
复制
my_dict = {
    "key1": "value1",
    "key2": {
        "subkey1": "subvalue1",
        "subkey2": "subvalue2"
    },
    "key3": "value3"
}

nested_list = convert_dict_to_nested_list(my_dict, "keyword")
print(nested_list)

输出结果为:

代码语言:txt
复制
[['key1', 'value1'], ['key2', [['subkey1', 'subvalue1'], ['subkey2', 'subvalue2'], ['keyword']]], ['key3', 'value3'], ['keyword']]

在这个示例中,字典my_dict被转换为嵌套列表nested_list,并在每个子列表中插入了关键字"keyword"。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券