如何将多个列表添加到嵌套字典中? [英] How to append multiple lists to a nested dictionary?
本文介绍了如何将多个列表添加到嵌套字典中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有三个列表:
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}}
这篇关于如何将多个列表添加到嵌套字典中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文