如何将多个列表添加到嵌套字典中?
问题描述:
假设我有三个列表:
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}}