Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append multiple lists to a nested dictionary? [duplicate]

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

like image 643
superasiantomtom95 Avatar asked Jan 03 '23 07:01

superasiantomtom95


1 Answers

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}}
like image 132
Ajax1234 Avatar answered Jan 13 '23 15:01

Ajax1234