4

Suppose I have three lists:

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}

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

superasiantomtom95
  • 491
  • 1
  • 6
  • 21

1 Answers1

9

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)}

Output:

{1: {'a': 4}, 2: {'b': 5}, 3: {'c': 6}}
Ajax1234
  • 66,333
  • 7
  • 57
  • 95