如何将多个列表添加到嵌套字典中?

编程入门 行业动态 更新时间:2024-10-22 13:38:57
本文介绍了如何将多个列表添加到嵌套字典中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有三个列表:

list_a = [1,2,3] list_b = ['a','b','c'] list_c = [4,5,6]

如何创建如下所示的嵌套字典:

How do I create a nested dictionary that looks like this:

dict = {1:{'a':4},2:{'b':5},3:{'c':6}

我当时在考虑使用collections模块中的defaultdict命令或创建一个类,但我不知道该怎么做

I was thinking of using the defaultdict command from the collections module or creating a class but I don't know how to do that

推荐答案

您可以利用zip和字典理解来解决此问题:

You can utilize zip and dictionary comprehension to solve this:

list_a = [1,2,3] list_b = ['a','b','c'] list_c = [4,5,6] final_dict = {a:{b:c} for a, b, c in zip(list_a, list_b, list_c)}

输出:

{1: {'a': 4}, 2: {'b': 5}, 3: {'c': 6}}

更多推荐

如何将多个列表添加到嵌套字典中?

本文发布于:2023-11-23 15:54:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622030.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   嵌套   如何将   字典   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!