Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create Nested Dictionary in Python with 3 lists

Let us Suppose, I have created 3 lists and I want to create a dictionary for it. e.g.

a= ['A', 'B', 'C', 'D']
b =[1, 2, 3, 4]
c = [9, 8, 7, 6]

Now What I want is to create a dictionary like this:

{'A':{'1' :'9'} , 'B':{'2':'8'}, 'C':{'3':'7'} , 'D':{'4':'6'}}

is it possible, Can Someone Help me on this?

like image 996
TeSter Avatar asked Dec 22 '17 16:12

TeSter


People also ask

How do you create a nested dictionary from a list Python?

To create a nested dictionary, simply pass dictionary key:value pair as keyword arguments to dict() Constructor. You can use dict() function along with the zip() function, to combine separate lists of keys and values obtained dynamically at runtime.

Can you create a dictionary from a list in Python?

You can convert a Python list to a dictionary using the dict. fromkeys() method, a dictionary comprehension, or the zip() method. The zip() method is useful if you want to merge two lists into a dictionary.

Can a dictionary be nested in Python?

In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries into one single dictionary. Here, the nested_dict is a nested dictionary with the dictionary dictA and dictB . They are two dictionary each having own key and value.

How do you make a list into a dictionary?

To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.


2 Answers

You can create the dictionary from zip-ed lists and convert the int values to strings - if I understood your question proper

dct = {x: {str(y): str(z)} for x, y, z in zip(a,b,c)}

Output:

{'A': {'1': '9'}, 'C': {'3': '7'}, 'B': {'2': '8'}, 'D': {'4': '6'}}
like image 136
atru Avatar answered Oct 19 '22 22:10

atru


You can also use map() here:

a = ['A', 'B', 'C', 'D']
b = [1, 2, 3, 4]
c = [9, 8, 7, 6]

dct = dict(map(lambda x, y, z : (x, {str(y): str(z)}), a, b, c))

print(dct)

Which outputs:

{'A': {'1': '9'}, 'B': {'2': '8'}, 'C': {'3': '7'}, 'D': {'4': '6'}}
like image 39
RoadRunner Avatar answered Oct 19 '22 23:10

RoadRunner