本文介绍了如何将多个列表添加到嵌套字典中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有三个列表:
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}}更多推荐
如何将多个列表添加到嵌套字典中?
发布评论